【发布时间】:2013-04-01 02:51:57
【问题描述】:
我有以下代码...
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});
});
按照目前的工作方式,当按下蓝色按钮时,容器会滚动到顶部 2990 像素和左侧 1990 像素,并且黄色项目进入视野(在其顶部和左侧留下 10 像素的间隙),这就是我想让它做。
但是,我想知道是否可以将其更改为公式,以便根据项目 div 的左侧和顶部位置设置 scrollTop 和 scrollLeft 值。允许我更改 div 的左侧和顶部位置,而不必担心编辑我的 jquery。
我可以在脑海中看到公式,但只是不知道如何在 jQuery 中实现它。公式应该类似于...
'scrollTop' = (("#item" top) - 10px)
而不是
'scrollTop': '2990px'
和
'scrollLeft' = (("#item" left) - 10px)
而不是
'scrollLeft': '1990px'
所以它找到#item div 的'top' 和'left' 的值,然后从它们中减去10 个像素。
我只是不知道如何将该公式写入我的 jQuery,因为我还不是很精通它。
谁能帮帮我?
【问题讨论】:
标签: jquery scroll jquery-animate formula