我一直试图得到一个滚动到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;

其他回答

问题是JQuery。最简单的应该是下面的代码。确保包含了JQueryUI。用最新的版本替换{version},当然这里是你可以用于动画的所有方法的列表。2秒的easeOutExpo将给你非常艺术的滚动。

线性, 摆动, easeOutQuad, easeInQuad, easeInOutQuad, easeOutCubic, easeInCubic, easeInOutCubic, easeOutQuart, easeInQuart, easeInOutQuart, easeOutQuart, easeOutQuint, easeInOutQunit, easeOutExpo, easeInExpo, easeInExpo, easeInOutSine, easeInSine, easeInSine, easeOutSine, easeOutSine, easeInCirc, easeInOutCirc, easeInOutCirc, easeOutCirc, easeInElastic, easeInElastic, easeInElastic, easeOutBack, easeInBack, easeInOutBack, easeOutBack, easeOutBounce, easeInOutBounce, easeInOutBounce

<script src="https://code.jquery.com/ui/{version}/jquery-ui.js"></script>

$('html, body').animate({ scrollTop: $("#id").offset().top }, 1000, "easeInExpo");

我试了一下,效果很好。

$('a[href*="#"]').on('click', function (e) {
    e.preventDefault();

    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
    }, 500, 'linear');
});

HTML:

 <a href="#fast-food" class="active" data-toggle="tab" >FAST FOOD</a>

<div id="fast-food">
<p> Scroll Here... </p>
  </div>

这段代码对于网络上的任何内部链接都很有用

    $("[href^='#']").click(function() {
        id=$(this).attr("href")
        $('html, body').animate({
            scrollTop: $(id).offset().top
        }, 2000);
    });

如果你想覆盖页面上的标准href-id导航,而不改变平滑滚动的HTML标记,使用这个(示例):

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});

你需要动画html,主体

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

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