我有一个包含几个<div>
个容器的页面。
如何在页面加载时关注其中一个,以便用户可以使用箭头键滚动(甚至 SPACE 滚动),而无需点击div
第一λ
我试过了:
<div id="main" autofocus>
但autofocus
似乎无法处理非输入div
。
_
此可能是一个解决方案,但浏览器地址栏会显示我不想要的ID http://example.com/#main:
<body onload="location.hash = 'main';">
<div id="main">content</div>
</body>
_
示例:当您打开https://en.wikipedia.org/wiki/Main_Page时,您可以立即使用向下箭头键或 Space 滚动,而无需点击任何地方。
答案 0 :(得分:2)
您可以使用JavaScript来聚焦元素,使用tabindex来聚焦元素。
document.querySelector(".focus").focus();
.focus {
height: 100px;
width: 100px;
overflow: scroll;
}
<div>Hello</div>
<div>Another div</div>
<div class="focus" tabindex="0">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<div>Bye</div>
答案 1 :(得分:1)
焦点事件用于输入元素。请改用click
事件:
document.querySelector('#main').click();
另外,使用tabindex
绑定非输入元素上的键盘事件:
<div id="main" tabindex="0">main content</div>
答案 2 :(得分:0)
要关注非输入元素,您需要tabIndex
并使用focus
方法。autofocus适用于选定的元素集
document.getElementById("main").focus()
#main:focus {
border: 1px solid;
}
<div id="main" tabindex="1">hello</div>
答案 3 :(得分:0)
首先,您需要向tabindex="-1"
添加div#main
以使其在程序上具有焦点。然后使用javascript获取div并使其集中。
以下是一个片段:确保在window.onload
事件中添加代码或将脚本标记直接放在</body>
HTML:将tabindex属性添加到div#main
<div id="main" tabindex="-1">
JavaScript:让div#main
专注
document.getElementById("main").focus();
如果您在点击时需要做一些事情,那么它会自动聚焦并仍然接受点击事件!
希望我能够让你更进一步。