首页 文章

Javascript固定页脚覆盖焦点

提问于
浏览
-1

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

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

当用户选中字段并将焦点设置在静止页脚下方的元素上时,页面不会向上滚动以显示聚焦元素 . 有没有办法使用JavaScript自动滚动,以确保焦点元素始终出现在页脚上方?

2 回答

  • 0

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

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

    function setFocusToElement () {
          var element = document.getElementById("yourelement");
          element.focus();
          element.scrollIntoView();
        }
    
  • 1

    如果您的所有输入字段都是 <input> ,则可以使用JavaScript执行此操作:

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

    这应该做三件事:

    • 遍历每个 <input> 元素

    • 为每个 <input> 元素添加 onfocus 事件侦听器

    • 将窗口位置设置为文件名,以及针对刚刚关注的元素的#标签选择器 .

    希望这对你有所帮助!

    这是一个jQuery方式做同样的事情:

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

    稍微简单,但它做同样的事情 .

相关问题