jquery顺利滚动到锚点?

dyn*_*mic 61 javascript jquery

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

喜欢:

$(document).ready(function(){
  $("#gotomyanchor").click(function(){
      $.scrollSmoothTo($("#myanchor"));
  });
});
Run Code Online (Sandbox Code Playgroud)

han*_*noo 121

我是这样做的:

    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;
        }
    });
Run Code Online (Sandbox Code Playgroud)

然后你只需要像这样创建你的锚:

<a class="scroll" href="#destination1">Destination 1</a>
Run Code Online (Sandbox Code Playgroud)

你可以在我的网站上看到它.
这里也有一个演示:http://jsfiddle.net/YtJcL/

  • 我猜动画会很难切断,因为jQuery会尝试设置指定长度的动画,浏览器会在窗口到达结束时停止滚动. (6认同)
  • 检查以查看可以滚动的最低点是什么意思?如果你试图滚动到最后一个窗口高度以下,有些浏览器会搞乱吗?Chrome似乎并不介意; 即,设置`scrollTop:veryHighNumber`只会将您带到页面底部. (3认同)
  • @JamieCollingwood dest = $(this.hash).offset().top-50; 我认为这样做会有所帮助. (3认同)

小智 47

我会使用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;
      }
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

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

  • 呃,不知道这个片段是如何工作的。应该是 `$('a[href*="#"]:not([href="#"])')` (2认同)

aru*_*zca 38

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

HTML:

<a href="#comments" class="scroll">Scroll to comments</a>
Run Code Online (Sandbox Code Playgroud)

脚本:

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

  • 这真的是最简单的解决方案,再加上您希望平滑滚动的任何未来链接,只需将类"滚动"添加到链接即可. (2认同)

Mar*_*iek 12

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

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

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

  • 是的,它是一个插件,所以你需要下载并包含它.它虽然很轻巧,但功能非常棒.(注意:除了在很多网站上使用它之外,我没有任何个人联系) (3认同)