控件 focused 无效
Ensuring that a website or web app is both accessible and usable, as well as functional, is paramount to a positive user experience for all users. Users don't appreciate when we've done a good job, but they definitely know when we've done poorly. One important part of app usability and accessibility is focus management, a task often overlooked by developers.
确保网站或Web应用程序既可访问又可用,并且功能正常,这对于所有用户都具有积极的用户体验至关重要。 当我们做得很好时,用户不会欣赏,但是当我们做得不好时,用户肯定会知道。 应用程序可用性和可访问性的重要组成部分是焦点管理,这是开发人员经常忽略的一项任务。
A prime example of poor focus management: opening a modal upon clicking a triggering link, not focusing on the any element in the modal. Even worse: focusing on one of the modal's elements but not returning focus to its trigger element once it has been closed. Ideally you would store a reference to the trigger, focus into the modal, and focus back on the trigger element when the modal is closed.
焦点管理不善的一个典型示例:单击触发链接时打开模式,而不关注模式中的任何元素。 更糟糕的是:专注于模式的一个元素,但是一旦关闭,就不会将焦点返回到其触发元素。 理想情况下,您将存储对触发器的引用,将焦点集中在模式中,并在关闭模式时将焦点集中在触发器元素上。
What about the times when you aren't aware of which element is focused though? The document tells us which element is focused via the document.activeElement
property!
但是,当您不知道关注哪个元素时又会怎样呢? 该文档通过document.activeElement
属性告诉我们聚焦哪个元素!
JavaScript (The JavaScript)
Retrieving the currently selected element is as easy as using document.activeElement
:
检索当前选定的元素就像使用document.activeElement
一样容易:
var focusedElement = document.activeElement;
/* per my example:
var triggerElement = document.activeElement;
myModal = new MyModal({
onOpen: function() {
this.container.focus();
},
onClose: function() {
triggerElement.focus();
}
});
*/
This property isn't simply reserved for traditionally focusable elements, like form fields and links, but also any element with a positive tabIndex set.
此属性不仅仅保留给传统上可聚焦的元素(如表单字段和链接)保留,还保留给tabIndex设置为正的任何元素。
What I love about document.activeElement
is that you don't need any type of event listener or delegated listener to keep track of what element is focused -- you can simply reference that one property at any time. Of course you should do loads of testing before relying on a feature like this -- it seems ripe for cross-browser issues or race conditions. All in all, however, I've been pleased with my use of it and its reliability!
我喜欢document.activeElement
是,您不需要任何类型的事件侦听器或委托侦听器即可跟踪要聚焦的元素-您可以随时简单地引用该属性。 当然,在依赖这样的功能之前,您应该做大量的测试-跨浏览器问题或竞争条件似乎已经成熟。 总而言之,我对它的使用及其可靠性感到满意!
控件 focused 无效