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

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

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

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

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

毫无进展。


当前回答

普通 JS:

如果你使用现代浏览器,可以在纯JS中完成。

document
    .getElementById("range-calculator")
    .scrollIntoView({ behavior: "smooth" });

浏览器支持是一个小问题,但现代浏览器支持它。

其他回答

您可以使用以下简单的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 scrollTo插件文件吗?

你可能会在控制台中得到一个object: method not found "scrollTo"错误。

scrollTO方法不是jquery的原生方法。要使用它,你需要包含jquery scroll to插件文件。

裁判: http://flesler.blogspot.in/2009/05/jqueryscrollto-142-released.html http://flesler.blogspot.in/2007/10/jqueryscrollto.html

溶液: 将此添加到头部部分。

<script src="\\path\to\the\jquery.scrollTo.js file"></script>

这对我很管用。

<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>

谢谢。

下面是我的解决方案,平滑滚动到div /锚使用jQuery,以防你有一个固定的标题,这样它就不会在它下面滚动。 同样,如果你从其他页面链接它。

只需替换”。Site-header”到包含标题的div。

$(function() {

$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
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 - headerheight)
    }, 1000);
    return false;
  }
}
});

//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
  var target = $('#'+location.href.split("#")[1]);
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top - headerheight
    }, 1);
    return false;
  }
}
});