繁体   English   中英

删除div时如何保留当前视口?

[英]How do I preserve the current viewport when removing a div?

请参阅JSFiddle 本质上,我有3个非常长的div。 在第二个div的末尾,我有一个按钮,单击该按钮将删除第一个div。 问题在于,删除此div会使页面滚动到末尾。 发生这种情况时,如何防止这种行为并使视口保持完整?

<div id="first">
    <p>Some really long content ...</p>
</div>
<div id="second">
    <p>Some really long content... </p>
</div>
<button onclick="$('#first').remove()">Remove First div</button>
<div id="third">
    <p>Some really long content ...</p>
</div>

您所解释的行为是预期的。 要保持在当前位置,您需要调整视口滚动的位置。 例如,在您的jsfiddle中更新: http : //jsfiddle.net/d0fqts8p/1/

$('button').click(function () {
    var firstElHeight = $('#first').height();  // get the height of element to be deleted
    var currentHeight = $("body").scrollTop(); // get the current scroll position
    $('#first').remove();
    $("body").scrollTop( currentHeight - firstElHeight);  //calculate and set back
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM