页面加载时,锚点滚动滚动到锚点

时间:2018-11-08 16:34:38

标签: javascript jquery

任何帮助,我们将不胜感激!我的产品页面顶部有一个按钮,用于显示尺码表,锚定滚动到页面底部的尺码表图像。但是,页面加载后,页面会自动向下滚动到尺寸表。我可以修改什么,以使页面不会自动向下滚动到锚点?这是我的JS:

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

1 个答案:

答案 0 :(得分:0)

我认为您的意思是页面在重新加载时向下滚动。

浏览器的默认行为是将页面向下滚动到用户最后一次访问该页面的位置。

为避免在关闭页面前滚动到顶部

$(window).on('beforeunload', function() {
    $(window).scrollTop(0);
});