【问题标题】:How to scroll to an element when a link is clicked [duplicate]单击链接时如何滚动到元素[重复]
【发布时间】:2014-04-29 09:30:04
【问题描述】:

所以我有以下网站: http://www.gameplay-universe.uphero.com/

您可以看到“跳至内容”链接。我希望在单击页面时滚动到div#content。我正在使用最新版本的 jQuery。我怎样才能做到这一点?

【问题讨论】:

标签: javascript jquery html


【解决方案1】:
$(document).scrollTop($('div#content').offset().top)

【讨论】:

    【解决方案2】:

    这是我想要启用“滚动到”类型的 Jquery 效果时喜欢使用的脚本。

    http://cferdinandi.github.io/smooth-scroll/

    【讨论】:

      【解决方案3】:
      $("li a").click(function(){
          $('html, body').animate({
              scrollTop: $( $.attr(this, 'href') ).offset().top
          }, 1000);
          return false;
      }); 
      

      这适用于 li 元素内的所有链接。

      【讨论】:

      • 由于我是 jQuery 新手,我应该编辑哪些变量以使其滚动到 div#content onclick li.skip a
      • $("#skip a").click(function(){ $('html, body').animate({ scrollTop: $("#content").offset().top }, 1000); 返回 false; });
      【解决方案4】:

      好的,这是我找到的解决方案:

      $(document).ready(function() {
      
      // Click event for any anchor tag that's href starts with #
      $('a[href^="#"]').click(function(event) {
      
          // The id of the section we want to go to.
          var id = $(this).attr("href");
      
          // An offset to push the content down from the top.
          var offset = 60;
      
          // Our scroll target : the top position of the
          // section that has the id referenced by our href.
          var target = $(id).offset().top - offset;
      
          // The magic...smooth scrollin' goodness.
          $('html, body').animate({scrollTop:target}, 500);
      
          //prevent the page from jumping down to our section.
          event.preventDefault();
      });
      });
      

      这对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-24
        • 2017-01-16
        • 2014-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-12
        相关资源
        最近更新 更多