我有一个页面有几个 <div>包含容器。
如何在页面加载时将焦点放在其中之一,以便用户可以使用箭头键滚动(甚至SPACE滚动)而无需单击div一个?
我试过了:
<div id="main" autofocus>
Run Code Online (Sandbox Code Playgroud)
但autofocus似乎不适用于 non-input div。
_
这可能是一个解决方案,但浏览器地址栏会显示我不想要的 id http://example.com/#main:
<body onload="location.hash = 'main';">
<div id="main">content</div>
</body>
Run Code Online (Sandbox Code Playgroud)
_
示例:当您打开https://en.wikipedia.org/wiki/Main_Page 时,您可以立即使用Down arrow键 或Space滚动,而无需单击任何地方。
您可以使用 JavaScript 来聚焦元素,并使用 tabindex 来让元素获得焦点。
document.querySelector(".focus").focus();Run Code Online (Sandbox Code Playgroud)
.focus {
height: 100px;
width: 100px;
overflow: scroll;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)