【问题标题】:jquery smooth scroll to an anchor?jquery 平滑滚动到锚点?
【发布时间】:2010-11-16 19:17:03
【问题描述】:

有没有办法使用 jQuery 向下滚动到锚链接?

喜欢:

$(document).ready(function(){
  $("#gotomyanchor").click(function(){
      $.scrollSmoothTo($("#myanchor"));
  });
});

?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

到目前为止我见过的最佳解决方案: jQuery: Smooth Scrolling Internal Anchor Links

HTML:

<a href="#comments" class="scroll">Scroll to comments</a>

脚本:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
});

【讨论】:

  • 这确实是最简单的解决方案,再加上您想要平滑滚动的任何未来链接,只需将“滚动”类添加到链接。
  • 这个版本打破了指向其他页面的锚点。
【解决方案2】:

作品

$('a[href*=#]').each(function () {
    $(this).attr('href', $(this).attr('href').replace('#', '#_'));
    $(this).on( "click", function() {

        var hashname = $(this).attr('href').replace('#_', '');

        if($(this).attr('href') == "#_") {
            $('html, body').animate({ scrollTop: 0 }, 300);
        }
        else {
            var target = $('a[name="' + hashname + '"], #' + hashname),
                targetOffset = target.offset().top;
            if(targetOffset >= 1) {
                $('html, body').animate({ scrollTop: targetOffset-60 }, 300);
            }
        }
    });
});

【讨论】:

    【解决方案3】:

    我会使用来自 CSS-Tricks.com 的简单代码 sn-p:

    $(function() {
      $('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
            }, 1000);
            return false;
          }
        }
      });
    });
    

    来源http://css-tricks.com/snippets/jquery/smooth-scrolling/

    【讨论】:

    • 这可能是更好的解决方案,如果您希望所有页面内锚链接都滚动动画而没有任何多余的装饰等。否则 jQuery.scrollTo 有很多很酷的其他技巧(查看他们的演示页面)
    • 这是一个非常棒的插入式解决方案
    • 原则上 - 使用 code 而不是 links - meta.stackexchange.com/questions/8231/…
    • 请注意,pathname 属性不包含任何 get 变量,因此如果您的 url 仅与 get 变量不同,则此代码将不起作用。
    • 呃,不知道这个 sn-p 怎么可能工作。应该是$('a[href*="#"]:not([href="#"])')
    【解决方案4】:

    这是我的做法:

        var hashTagActive = "";
        $(".scroll").on("click touchstart" , function (event) {
            if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
                event.preventDefault();
                //calculate destination place
                var dest = 0;
                if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
                    dest = $(document).height() - $(window).height();
                } else {
                    dest = $(this.hash).offset().top;
                }
                //go to destination
                $('html,body').animate({
                    scrollTop: dest
                }, 2000, 'swing');
                hashTagActive = this.hash;
            }
        });
    

    那么你只需要像这样创建你的锚:

    <a class="scroll" href="#destination1">Destination 1</a>
    

    你可以在我的website上看到它。
    此处也提供演示:http://jsfiddle.net/YtJcL/

    【讨论】:

    • 检查可以滚动到的最低点有什么意义?如果您尝试滚动到最后一个窗口高度以下,某些浏览器会搞砸吗? Chrome 似乎并不介意。即,设置 scrollTop: veryHighNumber 只会将您带到页面底部。
    • 我猜动画会被非常困难地切断,因为 jQuery 会尝试对指定的完整长度进行动画处理,并且当窗口到达末尾时浏览器会停止滚动。
    • 如何使用这种技术使锚点从页面顶部偏移(比如说 50 像素)。
    • @JamieCollingwood dest=$(this.hash).offset().top-50;我认为这可以解决问题。
    • 不错的解决方案!请注意,该链接需要以id 而非锚name 为目标元素。在我更仔细地查看您的 Fiddle 之前,我假设是后者并且对此感到非常沮丧。干杯!
    【解决方案5】:

    使用hanoo's script我创建了一个jQuery函数:

    $.fn.scrollIntoView = function(duration, easing) {
        var dest = 0;
        if (this.offset().top > $(document).height() - $(window).height()) {
            dest = $(document).height() - $(window).height();
        } else {
            dest = this.offset().top;
        }
        $('html,body').animate({
            scrollTop: dest
        }, duration, easing);
        return this;
    };
    

    用法:

    $('#myelement').scrollIntoView();
    

    持续时间和缓动的默认值为 400 毫秒和“摆动”。

    【讨论】:

      【解决方案6】:

      jQuery.scrollTo 会做你想做的一切,甚至更多!

      你可以给它传递各种不同的东西:

      • 原始数字
      • 一个字符串('44'、'100px'、'+=30px'等)
      • 一个 DOM 元素(逻辑上是可滚动元素的子元素)
      • 一个选择器,将与可滚动元素相关
      • 要滚动到末尾的字符串“max”。
      • 一个字符串,指定滚动到容器该部分的百分比(例如:50% 转到 * 到中间)。
      • 哈希 { top:x, left:y }, x 和 y 可以是任何类型的数字/字符串,如上。

      【讨论】:

      • 这是一个插件吗?因为我试过了,但什么也没发生。我用这个:$.scrollTo("#addNewUA",800, {easing:'elasout'});
      • 是的,它是一个插件,因此您需要下载并包含它。不过它非常轻巧,功能也很棒。 (注意:除了在很多网站上使用它之外,我没有任何个人联系)
      【解决方案7】:

      这是我用来快速将 jQuery scrollTo 绑定到所有锚链接的代码:

      // Smooth scroll
      $('a[href*=#]').click(function () {
          var hash = $(this).attr('href');
          hash = hash.slice(hash.indexOf('#') + 1);
          $.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500);
          window.location.hash = '#' + hash;
          return false;
      });
      

      【讨论】:

      • 看起来您可能需要 jQuery scrollTo 插件才能使这段代码工作?
      【解决方案8】:

      我想要一个适用于 &lt;a href="#my-id"&gt;&lt;a href="/page#my-id"&gt; 的版本

      <script>        
          $('a[href*=#]:not([href=#])').on('click', function (event) {
              event.preventDefault();
              var element = $(this.hash);
              $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
          });
      </script>
      

      【讨论】:

        【解决方案9】:

        试试这个。这是我修改的 CSS 技巧中的代码,它非常简单,并且可以进行水平和垂直滚动。需要 jQuery。这是demo

        $(function() {
          $('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-10, scrollLeft:target.offset().left-10
                }, 1000);
                return false;
              }
            }
          });
        });
        

        【讨论】:

          【解决方案10】:

          我在我的网站中使用了这个:

          $(document).ready(function(){
          $('a[href^="#"]').on('click',function (e) {
              e.preventDefault();
          
              var target = this.hash,
              $target = $(target);
          
              $('html, body').stop().animate({
                  'scrollTop': $target.offset().top
              }, 1200, 'swing', function () {
                  window.location.hash = target;
              });
          });
          

          });

          您可以更改滚动速度,更改我默认使用的“1200”,它在大多数浏览器上都运行良好。

          将代码放在页面的&lt;head&gt; &lt;/head&gt; 标记之间后,您需要在&lt;body&gt; 标记中创建内部链接:

          <a href="#home">Go to Home</a>
          

          希望对你有帮助!

          Ps:别忘了打电话:

          &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"&gt;&lt;/script&gt;

          【讨论】:

            【解决方案11】:

            我在http://plugins.jquery.com/smooth-scroll/ 使用了插件Smooth Scroll。有了这个插件,您只需要包含一个指向 jQuery 和插件代码的链接:

            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
            <script type="text/javascript" src="javascript/smoothscroll.js"></script>
            

            (链接需要有 smoothScroll 类才能工作)。

            Smooth Scroll的另一个特点是URL中不显示ancor名称!

            【讨论】:

              【解决方案12】:

              我讨厌在我的代码中添加以函数命名的类,所以我把它放在一起。如果我停止使用平滑滚动,我会觉得应该检查我的代码,并删除所有 class="scroll" 的东西。使用这种技术,我可以注释掉 5 行 JS,整个网站更新。 :)

              <a href="/about">Smooth</a><!-- will never trigger the function -->
              <a href="#contact">Smooth</a><!-- but he will -->
              ...
              ...
              <div id="contact">...</div>
              
              
              <script src="jquery.js" type="text/javascript"></script>
              <script type="text/javascript">
                  // Smooth scrolling to element IDs
                  $('a[href^=#]:not([href=#])').on('click', function () {
                      var element = $($(this).attr('href'));
                      $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
                      return false;
                  });
              </script>
              

              要求
              1.&lt;a&gt;元素必须有一个以#开头的href属性,并且不能只是#
              2. 页面上具有匹配id 属性的元素

              它的作用:
              1.函数使用href值创建anchorID对象
              - 在示例中,它是$('#contact')/about/ 开头
              2.HTMLBODY动画到anchorID的顶部偏移
              - speed = 'normal' ('fast','slow', 毫秒, )
              - 缓动 = 'swing'('线性'等......谷歌缓动)
              3. return false -- 防止浏览器在 URL 中显示哈希值
              - 没有它,脚本也能工作,但它不像“顺利”。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2013-08-14
                • 2013-11-16
                • 2019-05-05
                • 1970-01-01
                • 2014-08-08
                • 2014-10-26
                • 2023-04-02
                相关资源
                最近更新 更多