【问题标题】:How to scroll up or down the page to an anchor using jQuery?如何使用 jQuery 向上或向下滚动页面到锚点?
【发布时间】:2012-01-24 15:56:27
【问题描述】:

我正在寻找一种方法来添加幻灯片效果,以便您在页面上方或下方单击指向本地锚点的链接。

我想要一些你有这样链接的东西:

<a href="#nameofdivetc">link text, img etc.</a>

也许添加了一个类,以便您知道您希望此链接成为滑动链接:

<a href="#nameofdivetc" class="sliding-link">link text, img etc.</a>

然后,如果单击此链接,页面会向上或向下滑动到所需的位置(可以是 div、标题、页面顶部等)。


这是我之前的:

    $(document).ready(function(){
    $(".scroll").click(function(event){
        //prevent the default action for the click event
        event.preventDefault();

        //get the full url - like mysitecom/index.htm#home
        var full_url = this.href;

        //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
        var parts = full_url.split("#");
        var trgt = parts[1];

        //get the top offset of the target anchor
        var target_offset = $("#"+trgt).offset();
        var target_top = target_offset.top;

        //goto that anchor by setting the body scroll top to anchor top
        $('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
    });
});

【问题讨论】:

    标签: jquery jquery-plugins anchor slide


    【解决方案1】:

    说明

    您可以使用jQuery.offset()jQuery.animate() 执行此操作。

    查看jsFiddle Demonstration

    样本

    function scrollToAnchor(aid){
        var aTag = $("a[name='"+ aid +"']");
        $('html,body').animate({scrollTop: aTag.offset().top},'slow');
    }
    
    scrollToAnchor('id3');
    

    更多信息

    【讨论】:

    • 这也可以通用的用于页面中的所有内部锚链接:$("a[href^=#]").click(function(e) { e.preventDefault(); var dest = $(this).attr('href'); console.log(dest); $('html,body').animate({ scrollTop: $(dest).offset().top }, 'slow'); });
    • @bardo,它应该如何实现?我用你的替换了 dkmaack 的解决方案,但是滑动不存在(锚本身是功能性的)。我错过了什么?
    • @bardo 还添加了history.pushState(null, null, dest);,因为您正在阻止默认位置哈希更改
    • 仅供参考,除了@bardo 的解决方案,您应该在使用最新的 jQuery 时像这样转义哈希,$("a[href^=\\#]") stackoverflow.com/questions/7717527/…
    • 为 html 和 body 设置动画的目的是什么?看起来像我们不知道我们在做什么,只是做这一切的情况。这可能会引发多个 scollings 吗?
    【解决方案2】:

    我坚持使用我的原始代码,并在“返回顶部”链接中加入了一个淡入淡出,使用了这段代码,也从这里开始:

    http://webdesignerwall.com/tutorials/animated-scroll-to-top

    效果很好:)

    【讨论】:

      【解决方案3】:
      $(function() {
          $('a#top').click(function() {
              $('html,body').animate({'scrollTop' : 0},1000);
          });
      });
      

      在这里测试一下:

      http://jsbin.com/ucati4

      【讨论】:

      • 请不要包含签名,尤其是带有链接的签名...以及尤其是带有不相关链接的签名。你可以把这种东西放在你的个人资料中。
      • 问的问题不是如何滚动到页面顶部,而是如何滚动到带有 id 的锚点
      • 有没有办法可以在 WordPress 中使用它?我正在添加到我的网站,但它并没有真正起作用。这里是链接:scentology.burnnotice.co.za
      【解决方案4】:

      您可能需要添加 offsetTopscrollTop 值,以防您制作动画的不是整个页面,而是一些嵌套内容。

      例如:

      var itemTop= $('.letter[name="'+id+'"]').offset().top;
      var offsetTop = $someWrapper.offset().top;
      var scrollTop = $someWrapper.scrollTop();
      var y = scrollTop + letterTop - offsetTop
      
      this.manage_list_wrap.animate({
        scrollTop: y
      }, 1000);
      

      【讨论】:

        【解决方案5】:
        function scroll_to_anchor(anchor_id){
            var tag = $("#"+anchor_id);
            $('html,body').animate({scrollTop: tag.offset().top},'slow');
        }
        

        【讨论】:

        • 真正的问题,+"" 在第二行有什么作用吗?
        • @Rob javascript 没有字符串插值,因此将+ 与字符串或变量一起使用会连接它们,例如:"#some_anchor"。真的,我相信不需要第二个 concat anchor_id + ""
        • 谢谢@onebree 这是我想知道的第二个 concat :)
        【解决方案6】:

        这让我的生活变得轻松多了。你基本上把你的元素 id 标签和它的滚动到它没有很多代码

        http://balupton.github.io/jquery-scrollto/

        在 JavaScript 中

        $('#scrollto1').ScrollTo();
        

        在你的 html 中

        <div id="scroollto1">
        

        我一直在页面下方

        【讨论】:

        • 不起作用 - ScrollTo 不是函数
        【解决方案7】:

        以下解决方案对我有用:

        $("a[href^=#]").click(function(e)
                {
                    e.preventDefault();
                    var aid = $(this).attr('href');
                    console.log(aid);
                    aid = aid.replace("#", "");
                    var aTag = $("a[name='"+ aid +"']");
                    if(aTag == null || aTag.offset() == null)
                        aTag = $("a[id='"+ aid +"']");
        
                    $('html,body').animate({scrollTop: aTag.offset().top}, 1000);
                }
            );
        

        【讨论】:

          【解决方案8】:

          SS 慢速滚动

          此解决方案不需要锚标记,但您当然需要将菜单按钮(任意属性,例如“ss”)与 html 中的目标元素 id 匹配。

          ss="about"带你到id="about"

          $('.menu-item').click(function() {
          	var keyword = $(this).attr('ss');
          	var scrollTo = $('#' + keyword);
          	$('html, body').animate({
          		scrollTop: scrollTo.offset().top
          	}, 'slow');
          });
          .menu-wrapper {
            display: flex;
            margin-bottom: 500px;
          }
          .menu-item {
            display: flex;
            justify-content: center;
            flex: 1;
            font-size: 20px;
            line-height: 30px;
            color: hsla(0, 0%, 80%, 1);
            background-color: hsla(0, 0%, 20%, 1);
            cursor: pointer;
          }
          .menu-item:hover {
            background-color: hsla(0, 40%, 40%, 1);
          }
          
          .content-block-header {
            display: flex;
            justify-content: center;
            font-size: 20px;
            line-height: 30px;
            color: hsla(0, 0%, 90%, 1);
            background-color: hsla(0, 50%, 50%, 1);
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
          <div class="menu-wrapper">
            <div class="menu-item" ss="about">About Us</div>
            <div class="menu-item" ss="services">Services</div>
            <div class="menu-item" ss="contact">Contact</div>
          </div>
          
          <div class="content-block-header" id="about">About Us</div>
          <div class="content-block">
            Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
          
          That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
          </div>
          <div class="content-block-header" id="services">Services</div>
          <div class="content-block">
          Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
          
          That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
          </div>
          <div class="content-block-header" id="contact">Contact</div>
          <div class="content-block">
            Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
          
          That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
          </div>

          小提琴

          https://jsfiddle.net/Hastig/stcstmph/4/

          【讨论】:

          • 在我的情况下它正在工作,但页面在网站顶部向上。找不到为什么会这样。请问你能帮帮我吗?
          【解决方案9】:

          您还应该考虑到目标具有填充,因此使用position 而不是offset。您还可以考虑不希望与目标重叠的潜在导航栏。

          const $navbar = $('.navbar');
          
          $('a[href^="#"]').on('click', function(e) {
              e.preventDefault();
          
              const scrollTop =
                  $($(this).attr('href')).position().top -
                  $navbar.outerHeight();
          
              $('html, body').animate({ scrollTop });
          })
          

          【讨论】:

          • 恕我直言,这是最好的解决方案,因为它不需要额外的类和固定导航栏的 CSS 中烦人的填充数学
          • 但这不会重写 url 中的锚标记。添加history.pushState({}, "", this.href); 以保持网址更新
          【解决方案10】:

          假设您的 href 属性链接到带有 id 标记的 div 具有相同名称(像往常一样),您可以使用这段代码:

          HTML

          <a href="#goto" class="sliding-link">Link to div</a>
          
          <div id="goto">I'm the div</div>
          

          JAVASCRIPT - (Jquery)

          $(".sliding-link").click(function(e) {
              e.preventDefault();
              var aid = $(this).attr("href");
              $('html,body').animate({scrollTop: $(aid).offset().top},'slow');
          });
          

          【讨论】:

          • 非常简单但功能强大的解决方案,允许完全控制。我认为这个答案应该得到更多的支持。
          • 同意,这是最好的解决方案,对我帮助很大
          • 它有效,但违背了使用name 的目的。当您使用&lt;a name="something"&gt;&lt;/a&gt; 时,您也可以从外部引用它,但是您的解决方案不提供。
          【解决方案11】:

          我使用 jQuery 的方法只是让所有嵌入的锚链接滑动而不是立即跳转

          这与Santi Nunez 的答案非常相似,但它更可靠

          支持

          • 多框架环境。
          • 页面加载完成之前。
          <a href="#myid">Go to</a>
          <div id="myid"></div>
          
          // Slow scroll with anchors
          (function($){
              $(document).on('click', 'a[href^=#]', function(e){
                  e.preventDefault();
                  var id = $(this).attr('href');
                  $('html,body').animate({scrollTop: $(id).offset().top}, 500);
              });
          })(jQuery);
          

          【讨论】:

            【解决方案12】:

            这是对我有用的解决方案。这是一个通用函数,适用于所有引用命名 aa 标记

            $("a[href^=#]").on('click', function(event) { 
                event.preventDefault(); 
                var name = $(this).attr('href'); 
                var target = $('a[name="' + name.substring(1) + '"]'); 
                $('html,body').animate({ scrollTop: $(target).offset().top }, 'slow'); 
            });
            

            注意 1:确保在 html 中使用双引号 "。如果使用单引号,把上面部分代码改成var target = $("a[name='" + name.substring(1) + "']");

            注意 2:在某些情况下,特别是当您使用引导程序中的粘滞栏时,命名为 a 将隐藏在导航栏下方。在这些情况下(或任何类似情况),您可以减少滚动的像素数以达到最佳位置。例如:$('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow'); 将带您到顶部留有 15 个像素的target

            【讨论】:

            • 确保使用$("a[href^=\\#]")在你的jQuery选择器中转义#
            【解决方案13】:

            我在https://css-tricks.com/snippets/jquery/smooth-scrolling/ 上偶然发现了这个示例,它解释了每一行代码。我发现这是最好的选择。

            https://css-tricks.com/snippets/jquery/smooth-scrolling/

            你可以原生:

            window.scroll({
              top: 2500, 
              left: 0, 
              behavior: 'smooth' 
            });
            
            window.scrollBy({ 
              top: 100, // could be negative value
              left: 0, 
              behavior: 'smooth' 
            });
            
            document.querySelector('.hello').scrollIntoView({ 
              behavior: 'smooth' 
            });
            

            或使用 jquery:

            $('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {
            
                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) {
                    event.preventDefault();
                    $('html, body').animate({
                      scrollTop: target.offset().top
                    }, 1000);
                  }
                }
              });
            

            【讨论】:

              【解决方案14】:

              好的,最简单的方法是:-

              在点击函数内(Jquery):-

              $('html,body').animate({scrollTop: $("#resultsdiv").offset().top},'slow');
              

              HTML

              <div id="resultsdiv">Where I want to scroll to</div>
              

              【讨论】:

              • 这不会将锚点放在 url 中。动画后添加location.hash="#resultsdiv";
              猜你喜欢
              • 1970-01-01
              • 2013-09-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-04-04
              相关资源
              最近更新 更多