我有一个页面有几个 <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 ,您可以立即使用向下箭头 键或空格键 进行滚动,而无需点击任何地方。
最佳答案
您可以使用 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>
关于javascript - 自动对焦到 div,这样我们就可以使用箭头键滚动而无需先单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49084991/