代码之家  ›  专栏  ›  技术社区  ›  Peter Lange

Javascript固定页脚覆盖焦点

  •  -1
  • Peter Lange  · 技术社区  · 6 年前

    我有一个网页,我正在工作的网页有一个固定的页脚在页面底部。

    https://littlemouseproductions.blob.core.windows.net/example/Footer%20Example.PNG

    2 回复  |  直到 6 年前
        1
  •  1
  •   Farre    6 年前

    我想您正在寻找Element.scrollIntoView()函数。

    https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

        function setFocusToElement () {
          var element = document.getElementById("yourelement");
          element.focus();
          element.scrollIntoView();
        }
    
        2
  •  0
  •   Jack Bashford    6 年前

    如果所有输入字段都是 <input> s、 您可以使用JavaScript这样做:

    [].forEach.call(document.getElementsByTagName("input"), function(element) {
        element.addEventListener("focus", function(event) {
            window.location.href = location.pathname + "#" + event.target.id;
        })
    })
    

    1. 迭代每个 < 要素
    2. 添加 onfocus 每个事件的事件侦听器 < 要素
    3. 将窗口位置设置为文件名,再加上刚刚关注的元素的hashtag选择器。

    希望这对你有帮助!

    以下是jQuery做同样事情的方法:

    $("input").on("focus", function() {
        window.location.href = location.pathname + "#" + $(this).id;
    })
    

    稍微简单一点,但它做同样的事情。