Ссылка на привязку на другой странице с плавной прокруткой

Я много раз искал этот ответ, но не нашел его.

У меня есть якоря на домашней странице со ссылками в верхнем меню, которые прокручиваются до них.

Это отлично работает на домашней странице, но на подстраницах не работает.

Ниже мой код:

$(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 !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();
      event.stopPropagation();
      // 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
        }, 2000, function(){

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

До сих пор я обнаружил, что удаление строки event.preventDefault () заставляет их работать. Но это останавливает приятный эффект плавной прокрутки.

Что здесь можно изменить, чтобы я мог щелкать по ссылкам привязки на подстраницах, которые ведут к разделу привязки на домашней странице с плавной прокруткой?


person Kiki    schedule 18.07.2018    source источник
comment
Под подстраницей вы имеете в виду другую страницу? Если да, то с помощью прокрутки на другой странице вы хотите, чтобы страница загружалась вверху и плавно прокручивалась до привязки? Эти моменты можно прояснить, чтобы получить более точный ответ. Надеюсь, что так.   -  person vahdet    schedule 18.07.2018


Ответы (1)


используйте return false; вместо этого после прокрутки и удалите event.preventDefault & event.stopPropagation()

попробуйте ниже код:

$(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 !== "") {

      // 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
      }, 2000, function() {

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
      return false;
    } // End if
  });
});
person Shiv Kumar Baghel    schedule 18.07.2018
comment
Вау, это прекрасно! Работал как шарм! Большое спасибо за Вашу помощь!! - person Kiki; 18.07.2018
comment
было бы лучше в vanilla js - person AGrush; 16.06.2021