jQuery JavaScript 滚动到带有动画的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19498517/
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
JavaScript scroll to div with animation
提问by Luddig
I have a PhoneGap application that when it opens an HTML page, I want it to scroll to a specific <div>
element. So far I've been able to make it do that with this script using jQuery:
我有一个 PhoneGap 应用程序,当它打开一个 HTML 页面时,我希望它滚动到特定<div>
元素。到目前为止,我已经能够使用 jQuery 通过这个脚本来做到这一点:
<script>
$(document).delegate('.ui-page', 'pageshow', function () {
var offset = $(this).find('#timeindicatordiv').offset().top;
setTimeout(function () {
$.mobile.silentScroll(offset);
}, 0);
});
</script>
This only gives me a jump directly to the <div>
which looks a bit choppy.
这只会让我直接跳转到<div>
看起来有点波涛汹涌的 。
Is there any way to give this a smooth animation?
有什么办法可以使动画流畅?
回答by kyle.stearns
You can do the following:
您可以执行以下操作:
var scrollToElement = function(el, ms){
var speed = (ms) ? ms : 600;
$('html,body').animate({
scrollTop: $(el).offset().top
}, speed);
}
// specify id of element and optional scroll speed as arguments
scrollToElement('#timeindicatordiv', 600);
jsfiddle/example: http://jsfiddle.net/dtR34/4/
jsfiddle/示例:http: //jsfiddle.net/dtR34/4/
回答by Nelson
Do it like this:
像这样做:
$("html,body").animate({scrollTop: offset}, 600);
回答by Shrikant Gangamwar
$('.click').click(function(l){
// prevent default action
l.preventDefault();
scrollToElement( $(this).attr('href'), 2000 );
});
var scrollToElement = function(el, ms){
var speed = (ms) ? ms : 2000;
$('html,body').animate({
scrollTop: $(el).offset().top
}, speed);
}
div {
margin-top:1000px;
}
div:last-child {
padding-bottom:1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#link1" class="click">link 1</a><br />
<a href="#link2" class="click">link 2</a><br />
<a href="#link3" class="click">link 3</a><br />
<div id="link1">Link 1</div>
<div id="link2">Link 2</div>
<div id="link3">Link 3</div>