如何为 ScrollintoView 函数进行偏移

How to make offset for ScrollintoView function

提问人:HTMLNerd_1 提问时间:10/22/2023 更新时间:10/22/2023 访问量:33

问:

因此,我有几个按钮可以滚动到我网站的不同位置,并将其突出显示为黄色一秒钟。它们运行良好,但唯一的问题是,由于我的顶部导航很高,因此它滚动到的一些元素被覆盖了。有没有办法将属性偏移 45px(边框和合理边距的额外 5),这样它就不会被覆盖?谢谢!以下是其中一个按钮的代码:40pxscrollintoview

function Go_to_Q_and_A() {
    var divElement = document.getElementsByClassName('QA')[0];
    divElement.scrollIntoView();
    divElement.classList.add('highlighted');

    setTimeout(function() {
        divElement.classList.remove('highlighted');
    }, 1000);
}
javascript html 函数 js-scrollintoview

评论


答:

0赞 aabdulahad 10/22/2023 #1

非常简单的仅CSS解决方案,添加以下属性:
它会按照它所说的去做 - 在页面滚动中添加一个上边距,以便将固定导航栏考虑在内。
.QA { scroll-margin-top: 45px; }

function Go_to_Q_and_A() {
    var divElement = document.getElementsByClassName('QA')[0];
    divElement.scrollIntoView();
    divElement.classList.add('highlighted');

    setTimeout(function() {
        divElement.classList.remove('highlighted');
    }, 1000);
}
.QA { scroll-margin-top: 45px; }
.highlighted { background-color: yellow; }
.tall { height: 1000px }
<button onclick="Go_to_Q_and_A()">QA</button>
<div class="tall">Lorem</div>
<div class="QA">QA</div>
<div class="tall">Lorem</div>

评论

0赞 HTMLNerd_1 10/22/2023
谢谢!不过,我必须将其设置为才能正常工作scroll-margin-top:90px;