繁体   English   中英

jQuery追加销毁原始元素

[英]jQuery append destroying original element

我在网页顶部有一个div ,当用户向下滚动时,我想在其中添加内容。

我用sticky-item类标记要附加的内容。

问题在于,当将它们附加到页面顶部的sticky div时,它们会从HTML的原始位置被破坏,并且当用户向上滚动时无法替换。

这是一个JSFiddle

如何向后滚动,将元素附加到sticky div并将其替换为原始位置?

您需要克隆并附加其他内容,就像将dom元素从当前位置移动到新位置一样。

 $(document).ready(function () { var sticky = false; $(window).scroll(function (e) { if ($(this).scrollTop() > 50 && !sticky) { sticky = true; // Scroll up $('.sticky-item').clone().appendTo('.sticky'); } if ($(this).scrollTop() < 50 && sticky) { sticky = false; $('.sticky').empty(); } }); }); 
 .sticky { position: fixed; top:0; z-index: 100; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="container"> <div class="sticky"></div> <div class="row"> <h1>This is my text</h1> </div> <div class="row sticky-item"> <h2>This is some more text (pay attention it will be missing)</h2> </div> <div class="row"> <h3>and finally</h3> </div> <div class="row"> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> <p>this is more text</p> </div> </div> 

sticky标志用于避免多次追加

参见http://jsfiddle.net/wfrxujst/2/

克隆对象并删除其类,然后附加到div:

$(this).clone().removeClass("sticky-item").appendTo( ".sticky" );
$(this).hide();

滚动显示隐藏的项目:

 $('.sticky-item').show();

暂无
暂无

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

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