【问题标题】:Jquery smooth scroll - Only works properly when scroll bar is at the top when the link is clickedJquery 平滑滚动 - 仅当单击链接时滚动条位于顶部时才能正常工作
【发布时间】:2021-07-21 12:40:29
【问题描述】:

Javascript 新手,在这个问题上花了几个小时:/

我想实现平滑的滚动效果以移动到网页的不同部分。我正在使用这段 javascript。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('a').on('click', function(e) {
    if (this.hash !== '') {
        e.preventDefault();
        const hash = this.hash;

        $('html, body, .main')
            .animate({
                scrollTop: $(hash).offset().top
            }, 800);
    }
});

这是基本结构

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="margin-left: 30%; margin-right: 30%">
  <main>
    <a href="#contactme"><div class="contactme-button">Contact me</div></a>
  
    <div class="section-1" style="width: 100%; height: 1000px; background-color: grey; display: block;"> </div>
  
    <a href="#contactme"><div class="contactme-button-2">Contact me</div></a>
  
    <div class="section-1" style="width: 100%; height: 1000px; background-color: blue; display: block;"> </div>
  
    <div class="contactme-section" id="contactme" style="width: 100%; height: 100px; background-color: grey;">CONTACT ME</div>
    <div class="section-1" style="width: 100%; height: 1000px; background-color: black; display: block;"> </div>
  </main>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    $('a').on('click', function(e) {
        if (this.hash !== '') {
            e.preventDefault();
            const hash = this.hash;

            $('html, body, .main').animate({
                scrollTop: $(hash).offset().top
            }, 800);


        }
    });
</script>
</html>

(里面有更多内容,但这是让我伤心的基本结构)

我发现

.main{
overflow-x: hidden;
}

正在停止滚动的正常操作并导致第二个链接滚动到随机点

【问题讨论】:

标签: smooth-scrolling


【解决方案1】:

这里有一个 CSS 声明可能会有所帮助:

.your-anchor-element-class {
  scroll-margin-top: 36px; // <-- your value here
}

浏览器支持:原生支持 Chrome、FF、Edge、Opera。在 Safari 中使用 scroll-snap-margin-top 支持。

MDN docs.

感谢Josh Comeau 指出这一点。

【讨论】:

  • 谢谢,我发现在 .main{ overflow-x: hidden; } 正在停止滚动的正常操作并导致第二个链接滚动到随机点。任何线索为什么?
猜你喜欢
  • 2014-11-03
  • 2013-05-05
  • 2021-12-25
  • 2013-01-11
  • 1970-01-01
相关资源
最近更新 更多