Как сделать этот прокрутку на 120 пикселей выше содержимого? - PullRequest
0 голосов
/ 31 октября 2018

Когда я применяю этот скрипт, он идет по ссылке, но я хочу, чтобы он был на 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 голосов
/ 02 ноября 2018

проблема в 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);
});
0 голосов
/ 02 ноября 2018

Просто вычтите количество пикселей из вашего расчета.

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