jQuery 带偏移量的滚动顶部动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15784330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:48:08  来源:igfitidea点击:

Animate scrollTop with offset

jqueryjquery-uijquery-ui-accordion

提问by Graeme

I am using jQuery UI accordion but some of the text is too long which causes it to be neaer the top of the page. What i wanted was when a section was opened it would jump to the top of the section. This code works perfectly in doing that but it snaps to the top, which looks clitchy.

我正在使用 jQuery UI 手风琴,但有些文本太长导致它更接近页面顶部。我想要的是当一个部分被打开时它会跳到该部分的顶部。这段代码可以完美地做到这一点,但它会捕捉到顶部,这看起来很陈词滥调。

$('#accordion').bind('click',function(){
theOffset = $(this).offset();
$(window).scrollTop(theOffset.top - 50);
});

How would i animate the scrollTop so it "glides" to the top

我将如何为 scrollTop 设置动画,使其“滑动”到顶部

Many thanks

非常感谢

回答by Kaloyan

Use

$('body,html').animate({
    scrollTop: theOffset.top - 50
});

instead of

代替

$(window).scrollTop(theOffset.top - 50);

回答by Ejaz

use jquery animateto animatethe properties over specified time instead of just applying them instantly.

使用jQuery的动画动画在指定的时间,而不是仅仅将他们瞬间的属性。

$('#accordion').bind('click',function(){
    theOffset = $(this).offset();
    $('body,html').animate({
        scrollTop: theOffset.top - 50;
    });
});