我一直试图得到一个滚动到div id jquery代码正确工作。基于另一个堆栈溢出问题,我尝试了以下

演示http://jsfiddle.net/kevinPHPkevin/8tLdq/

$('#myButton').click(function() {
   $.scrollTo($('#myDiv'), 1000);
});

但这并没有起作用。我也试过了

$('#myButton').click(function(event) {
     event.preventDefault();
   $.scrollTo($('#myDiv'), 1000);
});

毫无进展。


当前回答

我的香草JS和jQuery的解决方案

香草JS:

document
    .querySelector("#myDiv")
    .scrollIntoView({ behavior: "smooth" });

jQuery:

你需要动画html,主体

$("#myButton").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

CSS:

html {
  scroll-behavior: smooth;
}

滚动行为的其他属性

scroll-behavior: auto|smooth|initial|inherit;

其他回答

再举一个例子:

HTML链接:

<a href="#featured" class="scrollTo">Learn More</a>

JS:

  $(".scrollTo").on('click', function(e) {
     e.preventDefault();
     var target = $(this).attr('href');
     $('html, body').animate({
       scrollTop: ($(target).offset().top)
     }, 2000);
  });

HTML锚:

  <div id="featured">My content here</div>

您可以使用以下简单的jQuery代码来实现这一点。

教程,演示和源代码可以从这里找到-使用jQuery平滑滚动到div

JavaScript:

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
        if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    });
});

HTML:

<a href="#section1">Go Section 1</a>
<div id="section1">
    <!-- Content goes here -->
</div>

你需要动画html,主体

演示http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

以下是我使用的方法:

<!-- jquery smooth scroll to id's -->   
<script>
$(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
        }, 500);
        return false;
      }
    }
  });
});
</script>

这种方法的优点在于,您可以使用无限数量的散列链接和相应的id,而不必为每个散列链接执行新脚本。

如果你使用的是WordPress,将代码插入到主题的footer.php文件中,就在body结束标签</body>之前。

如果您无法访问主题文件,则可以将代码嵌入到post/page编辑器中(必须以文本模式编辑文章)或将加载到所有页面的Text小部件上。

如果您使用的是其他CMS或HTML,则可以将代码插入到所有页面上加载的部分中,该部分位于body结束标记</body>之前。

如果你需要更多的细节,请查看我的快速帖子:jQuery平滑滚动到id

希望这对你有所帮助,如果你有任何问题,请告诉我。

这对我很管用。

<div id="demo">
        <h2>Demo</h2>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function () {
        // Handler for .ready() called.
        $('html, body').animate({
            scrollTop: $('#demo').offset().top
        }, 'slow');
    });
</script>

谢谢。