JS加载时平滑滚动会干扰单击时平滑滚动

问题描述 投票:-3回答:1

我是JS的新手,试图使以下代码起作用,以便主页在加载时自动滚动,而其他页面上的锚点链接在单击时平滑滚动...

<script>

    $(function(){
    $('html, body').animate({
    scrollTop: $('.destination').offset().top
    }, 2000);
    return false;

    $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 2000);
        return false;
      }
    }
   });
   });

</script>

任何帮助将不胜感激!

谢谢,安德烈亚斯

javascript jquery hyperlink anchor smooth-scrolling
1个回答
0
投票

这是因为您要通过提前返回false关闭函数。试试:

 $(function(){
    $('html, body').animate({
    scrollTop: $('.destination').offset().top
    }, 2000);

    $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 2000);
        return false;
      }
    }
   });
   });
© www.soinside.com 2019 - 2024. All rights reserved.