browser/HTML 如何决定光标的焦点应该在哪里?

How does browser/HTML decide where focus of cursor should be?

如果我们不使用 javascript 手动设置要聚焦的任何 HTML 元素,那么 HTML 如何决定聚焦哪个元素?

这是通过 tabindex attribute 完成的。默认情况下,它会按页面中的位置遍历可聚焦元素,但您可以修改此行为。

来自链接文章:

聚焦不可聚焦的元素:

tabindex=0

When tabindex is set to 0, the element is inserted into the tab order based on its location in the source code. If the element is focusable by default there’s no need to use tabindex at all, but if you’re repurposing an element like a span or div, then tabindex=0 is the natural way to include it in the tab order.

忽略一些可聚焦的元素:

tabindex=-1

When tabindex is set to a negative integer like -1, it becomes programmatically focusable but it isn’t included in the tab order.

最后:自行选择顺序,无论元素的位置如何:

tabindex=1+

It imposes a tab order on the content that bears no resemblance to the expected tab order.

实际上没有默认获得焦点的元素。

我们可以通过创建一个简单的站点和日志来很容易地检查这一点

document.querySelectorAll(":focus")

到控制台。

您会看到它将 return 一个空数组,这意味着没有元素被聚焦。

如果您的意思是 "What tells the browser which elements can be focused?",那么您正在寻找 tabindex 属性。将此添加到元素将允许输入设备(即鼠标、键盘)触发元素上的焦点状态。

如果您的问题基本上是 "how are things focused on?",这是使用输入设备完成的,即鼠标和键盘。

如果你的意思是当页面加载时你可以使用自动对焦属性

<input type="text" autofocus>