我有以下代码...
CSS
#container {
position:absolute;
height:100%;
width:100%;
top:0px;
left:0px;
overflow:scroll;
}
#content {
position:absolute;
height:5000px;
width:5000px;
top:0px;
left:0px;
background-image:url(http://subtlepatterns.com/patterns/purty_wood.png);
/* I used a background image so the scroll effect was more obvious */
}
#button {
position:absolute;
height:50px;
width:50px;
background-color:blue;
top:50px;
left:50px;
}
#item {
position:absolute;
height:250px;
width:750px;
background-color:yellow;
top:3000px;
left:2000px;
}
HTML
<div id="container">
<div id="content">
<div id="button"></div>
<div id="item"></div>
</div>
</div>
JQuery
$('#button').click(function() {
$('#container').animate({
'scrollTop': '2990px'
},{duration: 1000, queue: false});
$('#container').animate({
'scrollLeft': '1990px'
},{duration: 1000, queue: false});
});
就目前的情况而言,当按下蓝色按钮时,容器滚动到顶部 2990px 和左侧 1990px,黄色项目进入 View (在其顶部和左侧留下 10px 间隙),这就是我想要它做。
但是,我想知道是否可以将其更改为公式,以便它根据项目 div 的左侧和顶部位置设置scrollTop 和scrollLeft 值。允许我更改 div 的左侧和顶部位置,而不必担心编辑 jquery。
我可以在脑海中看到公式,但就是不知道如何将其实现到 jQuery 中。公式应该类似于...
'scrollTop' = (("#item" top) - 10px)
而不是
'scrollTop': '2990px'
和
'scrollLeft' = (("#item" left) - 10px)
而不是
'scrollLeft': '1990px'
因此,它找到 #item div 的“top”和“left”值,然后从中减去 10 个像素。
我只是不知道如何将该公式写入我的 jQuery,因为我还不太熟练。
有人可以帮助我吗?
最佳答案
只需使用 .position()
或 .offset()
即可获取元素的位置。
$('#button').click(function() {
$('#container').animate({
'scrollTop': $('#item').position().top - 10
},{duration: 1000, queue: false});
$('#container').animate({
'scrollLeft': $('#item').position().left - 10
},{duration: 1000, queue: false});
});
jsFiddle:http://jsfiddle.net/cr2W9/2/
关于jquery - 如何使用公式设置动画scrollTop 和scrollLeft 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15905943/