【问题标题】:Calculate the new top offset of the new added div after closing old divs计算关闭旧 div 后新添加 div 的新顶部偏移量
【发布时间】:2017-06-21 00:18:11
【问题描述】:

用户可以以这种形式添加块,因此我需要将新添加的块滚动到视图中并且它工作正常但是我尝试关闭旧块,例如打开的(块 2、块 3)然后滚动到(块 4)顶部偏移但它不起作用。

添加新块后,我将关闭旧打开的块并滚动到新块。

所以我需要在关闭旧 div(块 2、块 3)之后计算新 div(块 4)的新顶部偏移量,然后滚动到新偏移量。

以下代码仅在旧块保持其旧状态时才有效。

var curBlockOffsetTop = $(#divID).offset().top;

$('html, body').animate({
    scrollTop: curBlockOffsetTop - 40
}, 1000);

【问题讨论】:

    标签: javascript jquery scroll scrollview offset


    【解决方案1】:

    旧街区是如何关闭的?你的问题不够详细。

    听起来好像是 curBlockOffsetTop 在块关闭之前读取高度,然后当滚动动画触发时它滚动到错误的位置。如果是这种情况,请尝试使用 setTimeout 来延迟滚动的执行,直到所有内容都关闭。

    看起来像这样:

    /**closing old blocks code goes here**/
    
    var delayInMiliseconds = 1200;
    
    setTimeout(function(){
    
    /**scrolling code goes here**/
    
    }, delayInMiliseconds);
    

    【讨论】:

    • 我修改了问题,谢谢
    • 我仍然认为这是因为事件没有按照您希望的顺序执行。您是否尝试过像我建议的那样使用 setTimeout?
    【解决方案2】:

    如果不滚动到新块,而是滚动到最后一个块的末尾,怎么样?

    我不确定你的标记是怎样的,但假设它是这样的:

    <div class="block-1"></div>
    <div class="block-2"></div>
    <div class="block-3"></div>
    <div class="block-4">
       New Block that was just added
    </div>
    
    <script>
       newPosish = $(".block-3").offset().top $(".block-3").height() + 40 // where block-4 should be added
       window.scrollTo(0,newPosish)
    </script>
    

    【讨论】:

    • 这些是动态块,每个块都有自己的高度
    • 答案已编辑.. 正确,高度也需要添加
    • 非常感谢您的回答,但如果 (Block 2) 已打开(如图所示),则 (Block 3) 的顶部偏移量将在折叠两个块 (Block 2, Block 3)所以这是同一个问题,它计算旧的偏移量而不是折叠后的新偏移量
    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多