Jquery 如何使用公式设置动画scrollTop和scrollLeft值?

Jquery 如何使用公式设置动画scrollTop和scrollLeft值?,jquery,scroll,jquery-animate,formula,Jquery,Scroll,Jquery Animate,Formula,我有以下代码 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

我有以下代码

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>
当它当前工作时,当按下蓝色按钮时,容器滚动到顶部2990px和左侧1990px,黄色项目进入视图(在顶部和左侧留下10px的间隙),这就是我想要它做的

但是,我想知道是否可以将其转换为一个公式,这样它就可以根据项目div的左上位置设置scrollTop和scrollLeft值。这样我就可以更改div的左上位置,而不必担心编辑jquery

我可以在脑海中看到这个公式,但不知道如何在jQuery中实现它。公式应该类似于

'scrollTop' = (("#item" top) - 10px)
而不是

'scrollTop':  '2990px'
'scrollLeft':  '1990px'

而不是

'scrollTop':  '2990px'
'scrollLeft':  '1990px'
因此,它为#item div找到“top”和“left”的值,然后从中减去10个像素

我只是不知道如何将这个公式写入jQuery,因为我还不是很熟练


有人能帮我吗?

只需使用
.position()
.offset()
获取元素的位置即可


jsiddle:

只需使用
.position()
.offset()
获取元素的位置即可


jsFiddle:

太棒了!非常感谢!好极了非常感谢!
$('#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});
});