jQuery平滑滚动到锚点?

65

有没有一种使用jQuery滚动到锚链接的方法?

类似于:

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

?


这对我有用:https://css-tricks.com/snippets/jquery/smooth-scrolling/ - maahd
12个回答

122
这是我做的方法:
    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>

这里还有一个演示可用:http://jsfiddle.net/YtJcL/


3
检查滚动的最低点有什么意义?如果你尝试向下滚动超出窗口高度之外的部分,是否会导致某些浏览器出现问题?Chrome似乎不会出现问题,即使将scrollTop设置为非常大的数字,也只是让页面滚动到底部。 - Andrew
6
我猜测动画会被截断,因为jQuery试图对整个指定长度进行动画处理,但当窗口滚动到末尾时,浏览器会停止滚动。 - Strayer
1
如何使用这种技术使锚点偏移(比如说50像素)距离页面顶部。 - Jamie Collingwood
3
@JamieCollingwood dest=$(this.hash).offset().top-50; 我认为这样就可以解决问题了。 翻译说明: 将给定的代码片段进行翻译,保留原文意思,使之通俗易懂。 - Kyle
我已经在我的电脑上尝试过了,但它没有起作用。在jsfiddle上它是可以工作的。我尝试了很多JQuery版本,然后我从jsfiddle的结果中复制了代码,但它直接跳转到锚点。为什么? - artur99
显示剩余4条评论

49

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

$(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还有很多其他酷炫的技巧(请查看他们的演示页面)。 - Zach Lysobey
这是一个相当棒的即插即用解决方案。 - Talk nerdy to me
原则上 - 使用代码而不是链接 - http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers - Mars Robertson
请注意,pathname属性不包含任何get变量,因此如果您的URL仅因get变量而有所不同,则此代码将无法工作。 - Jay K
2
不知道这段代码怎么可能起作用。应该是 $('a[href*="#"]:not([href="#"])') - Dalin

42

到目前为止我看到的最佳解决方案: jQuery: 平滑滚动内部锚点链接

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
这确实是最简单的解决方案,如果您想要平滑滚动任何未来的链接,只需将类“scroll”添加到链接即可。 - Duncanmoo
此版本破坏了指向其他页面的锚点。 - Valerio Bozz

12

jQuery.scrollTo 可以满足你的所有需求,甚至还有更多功能!

你可以传递各种不同的参数:

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

这是一个插件吗?因为我尝试了一下,什么也没发生... 我使用了这个代码: $.scrollTo("#addNewUA",800, {easing:'elasout'}); - dynamic
3
是的,这是一个插件,所以您需要下载并包含它。虽然它非常轻巧,但功能非常出色。(注:我除了在很多网站中使用它之外没有任何个人关系) - Mark Biek

4

这是我用来快速绑定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;
});

1
看起来你可能需要使用jQuery scrollTo插件才能使这段代码正常工作? - Simon East

3
我希望能有一个版本可以同时支持 <a href="#my-id"><a href="/page#my-id">
<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>

2

试试这个。这是我修改过的来自CSS技巧的代码,非常简单明了,可以水平和垂直滚动。需要使用JQuery。这里有一个演示

$(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;
      }
    }
  });
});

1

作品

$('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);
            }
        }
    });
});

1

使用 hanoo的脚本,我创建了一个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毫秒和"swing"。


0

我使用了插件平滑滚动,位于http://plugins.jquery.com/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才能起作用。

平滑滚动的另一个特点是,在URL中不显示锚点名称!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接