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

标签 jquery scroll jquery-animate formula

我有以下代码...

jsFiddle

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/

相关文章:

javascript - 是否可以针对特定的 jQuery Ajax 调用禁用 Turbolinks 以防止页面刷新和滚动?

jquery - 使用javascript创建一个新库

javascript - Chrome 和 IE : parallax (jQuery animate) is not smooth when using mouse wheel to scroll

twitter-bootstrap - 动画 Bootstrap 进度条由于某种原因继续进行

javascript - jQuery 动画背景颜色

javascript - JavaScript 中的 anchor 元素

javascript - 以编程方式更改文本框值时 IE8 触发更改事件

html - 里面有文本的水平滚动框

javascript - JQuery 自动滚动到底部(但禁用鼠标滚动)

css - 溢出-x 不工作