Den*_*aia 7 html5 web-component
我正在编写一个旨在互动的自定义Web组件.如何告诉浏览器此自定义组件应该获得焦点?
我希望我的自定义元素......
:focus伪选择器匹配.我没有使用任何外部库,只使用简单的HTML5 API.
只需将tabindex属性添加到您想要可聚焦的元素即可.
// Add this to createdCallback function:
if (!this.hasAttribute('tabindex')) {
// Choose one of the following lines (but not both):
this.setAttribute('tabindex', 0);
this.tabIndex = 0;
}
// The browser automatically syncs tabindex attribute with .tabIndex property.
Run Code Online (Sandbox Code Playgroud)
单击该元素将使其成为焦点.按下选项卡将起作用.:focus在CSS中使用也会起作用.keydown和keyup事件工作,虽然keypress没有(但它已被弃用).在Chrome 44和Firefox 40上测试过.
另请注意,即使缺少HTML属性也会this.tabIndex返回-1,但这与设置有不同的行为tabindex="1":
<foo></foo>:没有tabindex属性,元素不可聚焦.<foo tabindex="-1"></foo>:该元素无法通过选项卡导航访问,但仍可通过单击进行聚焦.参考文献:
@Denilson,我想为您提供更多信息。
正如您所说,this.tabIndex = 0当您的 webcomponent 不包含可聚焦元素时有效。如果是这样,事情会变得更加复杂。
例如,如果您的组件包含一个或多个输入,那么首先“整个”组件获得焦点,然后在使用 Tab 键时,每个内部输入一个一个地获得焦点。这通常不是您想要的。通常,当组件获得焦点时,这意味着它的第一个输入立即获得焦点。
此外,还有一个反向跳转问题。如果您的第一个输入具有焦点并且您按下 SHIFT-TAB,则“整个”组件将获得焦点,您将被迫按 SHIFT-TAB 两次以移动到上一个元素。
我发现这可以解决所有焦点和制表问题:
// At first, the component may get focus and accept tabbing.
createdCallback = function () { this.tabIndex = 0; }
// When the component gets focus, pass focus to the first inner element.
// Then make tabindex -1 so that the component may still get focus, but does NOT accept tabbing.
focus = function (e) { firstFocusableInnerElement.focus(); this.tabIndex = -1; }
// When we completely left the component, then component may accept tabbing again.
blur = function (e) { this.tabIndex = 0; }
Run Code Online (Sandbox Code Playgroud)
注意:截至目前(2015 年 9 月),如果内部元素获得焦点,则“整个”元素与:focus伪选择器不匹配(仅在 Chrome 中测试)。如果发现这种行为是完全错误的。focus 事件被触发,而 blur 事件没有被触发。所以元素应该有焦点,对吧?我希望他们在未来改变这一点。
| 归档时间: |
|
| 查看次数: |
2502 次 |
| 最近记录: |