简体   繁体   English

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

[英]Anchor scroll is scrolling to the anchor upon page load

Any help with this is greatly appreciated! 任何帮助,我们将不胜感激! I have a button at the top of my product page for a sizing chart which anchor scrolls to the sizing chart image at the bottom of the page. 我的产品页面顶部有一个按钮,用于显示尺码表,锚定滚动到页面底部的尺码表图像。 However, upon page load, the page automatically scrolls down to the sizing chart. 但是,页面加载后,页面会自动向下滚动到尺寸表。 What can I modify so that the page does not automatically scroll down to the anchor? 我可以修改什么,以使页面不会自动向下滚动到锚点? Here is my JS: 这是我的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
          };
        });
      }
    }
  });

I assume you mean that the page scrolls down when it is reloaded. 我认为您的意思是页面在重新加载时向下滚动。

It is default browsers behaviour to scroll the page down to the point the user were the last time she/he visited the page. 浏览器的默认行为是将页面向下滚动到用户最后一次访问该页面的位置。

To avoid that scroll to top before the page is closed : 为了避免在关闭页面之前滚动到顶部:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM