首页 > 解决方案 > 如何使用 javascript 滑动到特定的 HTML 元素?

问题描述

单击按钮时如何设置焦点并向下滑动到 html。如何使用 javascript 滑动到特定的 HTML 元素?

p:focus, p:active {
  color: green;
}
p {
 min-height: 250px;
}
<body>


<input type="button" onclick="getfocus()" value="Get focus">
<input type="button" onclick="losefocus()" value="Lose focus">

<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p id="myAnchor">Click the buttons to give focus and/or remove focus from the link above.</p>

<script>
function getfocus() {
  document.getElementById("myAnchor").focus();
}

function losefocus() {
  document.getElementById("myAnchor").blur();
}
</script>

</body>

标签: javascripthtml

解决方案


添加tabindex="0"解决p#myAnchor问题

tabindex="0"意味着在任何正的 tabindex 值之后,元素应该在顺序键盘导航中是可聚焦的,并且它的顺序由文档的源顺序定义。

function getfocus() {
  document.getElementById("myAnchor").focus();
}

function losefocus() {
  document.getElementById("myAnchor").blur();
}
p:focus,
p:active {
  color: green;
}

p {
  min-height: 200px;
}
<input type="button" onclick="getfocus()" value="Get focus">
<input type="button" onclick="losefocus()" value="Lose focus">

<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p tabindex="0" id="myAnchor">Click the buttons to give focus and/or remove focus from the link above.</p>


推荐阅读