点击滚动到顶部100像素以上

On click scroll to the top with 100px more

本文关键字:100像素 顶部 滚动      更新时间:2023-09-26

我使用一个页面的网站,当我点击菜单按钮时,它向下滚动到一些div的顶部…但是因为我使用的是固定的标题滚动到顶部0px,我需要像100px的顶部填充在body标签中,但我需要在功能中说,我需要滚动到项目的顶部,从页面顶部到100px。下面是我的代码:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        var x = $(this.hash).offset().top;
        $('html,body').animate({scrollTop:x},2000);
    });
});

如果我理解正确的话,只要给$(this.hash).offset().top添加100px就可以了。

因为offset获取的是相对于文档的数据。

获取第一个元素的当前坐标,或者设置匹配元素集合中每个元素相对于文档的坐标。http://api.jquery.com/offset/

<标题>例子:

jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
    event.preventDefault();
    var x = $(this).offset().top;
    $('html,body').animate({scrollTop: x - 100 }, 2000);
  });
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body style="height: 1000px; padding-top: 100px">
<div class="scroll">click to scroll to me</div>
  
</body>
</html>