代码之家  ›  专栏  ›  技术社区  ›  gene b.

firefox:基于起始url的锚定和焦点输入字段

  •  0
  • gene b.  · 技术社区  · 8 年前

    这里有一些类似的线程讨论了这样一个事实:firefox没有正确地聚焦被锚定的元素,它们建议某种超时聚焦等。 focus() doesn't work with anchor link

    我从一个页面url开始。 http://myapp.com/page#elementID

    Firefox定位 elementID 页面加载正确(滚动到视图中),但它不会自动聚焦 元素ID 是的。我还需要专注于这个领域。

    当我将此添加到jquery文档中时。就绪,

    $(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 回复  |  直到 8 年前
        1
  •  1
  •   Louys Patrice Bessette    8 年前

    这个 .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);
    }
    

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