javascript - 自动对焦到 div,这样我们就可以使用箭头键滚动而无需先单击

标签 javascript html

我有一个页面有几个 <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/

相关文章:

javascript - 以 HTML 形式显示选项值,该值是 Google Apps 脚本代码的输出

html - 段落中的 "text-indent"如何申请?

html - 制作自定义边框html

Javascript parseFloat 和空值

javascript - Chrome 开发者工具 : What is Snippets Support?

javascript - 影子 DOM : what is shadow Dom and How to edit something inside it

javascript - 是否可以在 Vanilla Javascript 上使用部分名称获取元素?

html - 自动调整行大小的网格模板不起作用

html - 垂直居中溢出图像

javascript - 在函数中调用函数时处理参数的最佳方式