如何使此滚动条在内容上方120px?

时间:2018-10-31 13:26:44

标签: javascript jquery scroll smooth-scrolling

应用此脚本时,它会转到链接,但我希望它比链接到的内容高120px。

代码如下:

<script>
  $(document).ready(function(){
    // Add smooth scrolling to all links
    $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== 0) {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});
</script>

编辑#02

这是我的HTML,CSS和Java,适合那些想知道的人:

https://codepen.io/crosso_7/pen/WYegpY

2 个答案:

答案 0 :(得分:1)

只需从计算中减去像素量即可。

  $(document).ready(function(){
    // Add smooth scrolling to all links
    $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== 0) {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top -120
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

答案 1 :(得分:0)

问题是window.location.hash = hash;之后的animate会执行第二个操作,该操作与默认操作相同。将其替换为history.pushState(null, null, hash);以重写网址历史记录并添加哈希值

$('html, body').animate({
  scrollTop: $(hash).offset().top - 120
}, 800, function() {

  // Add hash (#) to URL when done scrolling (default click behavior)
  //window.location.hash = hash;
  history.pushState(null, null, hash);
});