Firefox:基于起始URL的锚定和焦点输入字段

时间:2018-06-28 18:39:06

标签: javascript jquery

这里有类似的话题,讨论Firefox无法正确关注锚定元素的事实,并且它们提出了某种超时关注等。 focus() doesn't work with anchor link

我从页面网址开始,例如 http://myapp.com/page#elementID

Firefox在页面上锚定elementID正确加载(滚动到视图中),但不会自动聚焦elementID。我还需要集中精力。

当我将其添加到jQuery Document.Ready中时,

$(document).ready(function() {

    // Handle the possible #-Anchor 
    // Firefox does not focus the anchored element (Chrome does).
    // Firefox workaround: If #-Anchor detected in URL, focus this element manually w/timeout
    if (window.location.href.indexOf("#") != -1) {
        var elementID = window.location.href.split("#")[1];
        setTimeout(function() {
            document.getElementById(elementID).focus();
        }, 10);
    }
}

然后焦点开始工作,但是锚定滚动 断开,即页面未正确滚动到锚定,页面被卡住了。

我如何同时同时使用“锚定和焦点”功能来为FF准备文档?

1 个答案:

答案 0 :(得分:1)

.focus()似乎正在将哈希滚动断开,这需要时间才能实现。

更长的延迟,但足够短的时间让用户不注意它,可以做到。


顺便说一句,您可以使用:

if (window.location.hash != "") {
    setTimeout(function() {
        $(window.location.hash).focus();
    }, 500);
}

代替:

if (window.location.href.indexOf("#") != -1) {
    var elementID = window.location.href.split("#")[1];
    setTimeout(function() {
        document.getElementById(elementID).focus();
    }, 10);
}

但这更多是关于代码“化妆品”的...
;)

相关问题