完善tab页面定位

当我们用锚点定位到页面某个元素时,接下来按tab的话是想进入到目前元素( id="content")的下一个连接
<a href="#content">Skip to Content</a>

<!-- other links -->

<div id="content">
    <!-- your content here -->
</div>
但是chrome 和 ie 有问题,按tab是选中 skip to Content之后的那个连接,修复方法就是在定位之后选中 content,通过修改 tabIndex
window.addEventListener("hashchange", function(event) {

    var element = document.getElementById(location.hash.substring(1));     //location.hash.substring(1) 指的是被点击的连接的href中的content

    if (element) {

        if (!/^(?:a|select|input|button|textarea)$/i.test(element.tagName)) {
            element.tabIndex = -1;
        }

        element.focus();
    }

}, false); 
tabIndex的值,根据W3C的规定,范围在0到 32767,通常只有表单元素可以设为focus,但是通过把tabIndex设置为-1,并且调用元素的focus函数,任何元素也可以实现(除了opera)
原文地址:https://www.cnblogs.com/chuangweili/p/5162747.html