【问题标题】:Firefox: Anchor and Focus Input Field based on Starting URLFirefox:基于起始 URL 的锚点和焦点输入字段
【发布时间】:2018-06-29 03:32:57
【问题描述】:

这里有类似的线程讨论 Firefox 没有正确聚焦锚定元素的事实,他们建议某种超时聚焦等。 focus() doesn't work with anchor link

我从页面 URL 开始,例如 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);
    }
}

然后焦点开始工作,但 锚滚动 中断,即页面没有正确滚动到锚点,它卡住了一点。

如何让两者锚和焦点在 Document Ready for FF 中工作?

【问题讨论】:

  • 您是否尝试过在 setTimeout 上设置更高的延迟?大概500...
  • 是的 500 个工作。 100还是没有。感谢您的提示

标签: javascript jquery


【解决方案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);
}

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

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 1970-01-01
    • 2018-09-23
    • 2014-10-27
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多