使用 JavaScript,如何判断用户是否向后切换?
我有一个 HTML 链接,并且我想在用户通过 Tab 键离开该链接时执行一些操作 - 但前提是用户在文档中向前移动而不是向后移动。
是否有一种可靠的跨浏览器方法来检测用户使用 Tab 键浏览文档的方式,或者是否确实使用 Tab 键浏览文档?我绑定到 blur
事件,但这并不一定意味着用户正在按 Tab 键。
我已经查看过检查 document.activeElement
的值,或者源中前一个可聚焦元素的 hasFocus
属性,但是:
- 这些看起来像是相对较新的添加,因此可能不会得到广泛支持,并且
- 我不确定当
blur
事件触发时它们是否可以检查,因为即使用户正在按 Tab 键,我认为下一个元素也不会还得集中注意力。
I've got an HTML link, and I want to take some action when the user tabs away from it - but only if the user is tabbing forwards through the document, as opposed to backwards.
Is there a reliable cross-browser way to detect which way the user is tabbing through the document, or indeed if they're tabbing through the document at all? I'm binding to the blur
event, but that doesn't necessarily mean that the user is tabbing.
I've had a look at inspecting the value of document.activeElement
, or the hasFocus
attribute of the previous focusable element in the source, but:
- those seem like relatively recent additions, and thus might not be widely supported, and
- I'm not sure they'll be inspectable when the
blur
event fires, as even if the user is tabbing, I don't think the next element will be focused yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须处理链接本身的
keydown
事件。检查这个 JSFiddle 示例,它检测特定链接上的向前和向后 Tab 键。
You will have to handle
keydown
event on the link itself.Check this JSFiddle example that detects forward and backward tabbing on a particular link.
作为 Robert 的良好解决方案的替代方案,也许您可以利用 tabindex 属性?为您的 html 链接和其他“可选项”项目设置它。然后在javascript中检查它。
使用 tabindex 的解决方案: jsfiddle
As an alternative to a good solution from Robert, maybe you can leverage tabindex attribute? Set it for your html links and other “tabbable” items. Then check it in javascript.
Solution with tabindex: jsfiddle