如何使用 jQuery animate() 函数在 div 内滚动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18545467/
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
How to scroll within a div with jQuery animate() function?
提问by Ram Patra
I have this code snippet which scrolls the entire body to a particular location →
我有这个代码片段,它将整个身体滚动到特定位置→
$('html, body').animate({ scrollTop: 1000}, 800, 'swing');
But what if i want to scroll to a particular location within a div like this →
但是如果我想像这样滚动到 div 中的特定位置怎么办 →
$('#div-id').animate({ scrollTop: 1000}, 800, 'swing');
I tried this way but its not working, can you tell me where i am going wrong?
我试过这种方式,但它不起作用,你能告诉我我哪里出错了吗?
NOTE: The element #div-id
has overflow:auto as one of its css rule.
注意:该元素#div-id
将 overflow:auto 作为其 css 规则之一。
回答by S. S. Rawat
Try this demo:
试试这个演示:
$('#div').scroll();
$("#div").animate({
scrollTop: 1000
}, 2000);
#div {
height: 100px;
overflow: scroll;
width: 200px;
border: 2px solid red;
}
<!DOCTYPE html>
<html>
<body>
<div id='div'>
dads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads
dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads dads dadsdads dadsdads dadsdads dadsdads dadsdads
dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dadsdads dads
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</body>
</html>
回答by Rahul Tripathi
How about trying like this:-
试试这样怎么样:-
function scrollingdiv(parentid, id){
$("#"+parentid).animate({scrollTop: $("#"+id).position().top}, 800, 'swing');
}