javascript - 如何使用 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>
解决方案
添加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>
推荐阅读
- c - C:对内联函数的未定义引用
- javascript - 如何在变量中的字符串中解析 Javascript 模板文字变量?
- python - 如何为与特定字符串变量的值对应的类属性赋值?
- reactjs - RadioGroup Onchange 没有在 React 中触发
- mysql - 通过加入 3 个表格计算百分比明智金额。还需要更改 INNER JOIN 以获取 COMMON 和 UNCOMMON 记录
- sql-server - 使用 SQL 和 SSRS 生成多个数组表
- swift - SwiftUI - 列表顺序
- tensorflow - 运行 Horovod 训练作业,遇到这个错误:只有秩的子集在提交张量,这会导致死锁
- selenium - Selenium 尝试弹出功能失败
- python - 从子类获取父类中的特定属性,而不将父类的属性传递给子类