scrollTop:如何在这个jquery脚本中工作

时间:2015-05-27 18:06:26

标签: javascript jquery jquery-animate

$(function(){ 我有以下代码可以使用。我是Jquery动画的新手。我想知道scrollTop函数在这里是如何工作的。因为在官方文档中,scrollTop前面没有冒号。这件事令我困惑。谢谢

$('a').bind('click', function (event) {
    var $anchor = $(this);

    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top
    }, 1500, 'easeInOutExpo');

    event.preventDefault(););
});

1 个答案:

答案 0 :(得分:0)

jsFiddle

你需要jQuery和jQuery UI才能使用缓动...在我的示例中使用onDomReady<a href='#your-element-id'>

,您的代码运行正常

<强> JS

// this binds any and all <a> elements onclick to this event
$('a').bind('click', function (event) {
    // this was moved to the top as to stop event default action
    event.preventDefault();
    // grabbing the <a> that was clicked and getting it's element
    var $anchor = $(this);

    // This first stops any and all animations that might be happening with .stop
    // then it kicks off an animation
    $('html, body').stop().animate({
        // scrollTop is the animation, we are grabbing the href value which should be declared as a selector with 1 result, then we are getting it's offset from the top (this will scroll up to that point [number of pixels from top])
        scrollTop: $($anchor.attr('href')).offset().top
    // we want this animation to last for 1.5 seconds and we are using
    // easeInOutExpo which from https://jqueryui.com/resources/demos/effect/easing.html shows will start slowly get to max speed then slow down at the end of the animation again 
    }, 1500, 'easeInOutExpo');
});