JQuery定位:我可以滚动到正确的位置一次,但不能滚动两次

JQuery positioning: I can scroll to the right place once but not twice

本文关键字:滚动 两次 一次 但不能 位置 我可以 定位 JQuery      更新时间:2024-06-13

我最近开始尝试在jQuery中模拟滚动到特定锚(太长了,读不下去了跳到锚会破坏页面的外部)。

虽然我在StackOverflow上发现的建议在第一次尝试向下滚动页面时有效,但我发现第二次尝试并不那么成功。

我可能已经考虑这个问题太久了,但我确实有一个基于我的困境的Fiddle:

http://jsfiddle.net/txns8bep/

var doThis = function() {
    var parent = $('#crud');
    var parentTop = $('#crud').offset().top;
    var targetTop = $('#2').offset().top;
    $(parent).animate({
        scrollTop: targetTop// - parentTop
    });
    console.log('doThis() called. Went to '+targetTop+'-'+parentTop);
};
// works the first time
doThis();
// doesn't work the second time
setTimeout(doThis, 1000);

HTML(部分)如下:

<div id="crud" style="position:absolute;top:100px;bottom:0;overflow:scroll; border:1px solid red;">
    <h1 id="1">Item #1</h1>Lorem ipsum....
    <h1 id="2">Item #2</h1>Ab magnam...
    <h1 id="3">Item #3</h1>Mollitia eius...
    <!-- (h1[id=$]{Item #$}+lipsum)*10 -->

不过,这个问题不仅仅是关于帖子滚动。如果当前偏移顶部大于0,则任何滚动到相关区域的尝试都会受阻。

(也许只是咖啡因在说话,但我被难住了。)

答案就在我面前:scrollTop()。我修改了动画功能如下,一切正常:

var newScrollTop = parent.scrollTop() + target.offset().top - parent.offset().top;
$(parent).animate({
    scrollTop: newScrollTop
});

http://jsfiddle.net/txns8bep/1/