首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jquery平滑滚动-只有在单击链接时滚动条位于顶部时,才能正常工作

问Jquery平滑滚动-只有在单击链接时滚动条位于顶部时,才能正常工作
EN

Stack Overflow用户
提问于 2021-07-21 20:40:30
回答 1查看 32关注 0票数 0

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

我想实现一个平滑的滚动效果,以移动到网页的不同部分。我正在使用这段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);
    }
});

这是基本结构

代码语言:javascript
复制
<!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>

(里面有更多的内容,但这是给我带来悲痛的基本结构)

我发现在

代码语言:javascript
复制
.main{
overflow-x: hidden;
}

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

EN

回答 1

Stack Overflow用户

发布于 2021-07-22 03:12:44

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

代码语言:javascript
复制
.your-anchor-element-class {
  scroll-margin-top: 36px; // <-- your value here
}

浏览器支持:在Chrome,FF,Edge,Opera中工作。在带有scroll-snap-margin-top的Safari中受支持。

MDN docs.

感谢Josh Comeau指出了这一点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68469660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档