如何使这个滚动条高于内容 120px?

How to make this scroll 120px above the content?

当我应用此脚本时,它会转到 link,但我希望它比 link 编辑到的内容高出 120 像素。

代码如下:

<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

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

  $(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
  });
});

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

$('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);
});