我的网页顶部有一个 div
,当用户向下滚动时,我想在其中添加内容。
我用 sticky-item
类标记了我想要 append 的东西。
问题是,当它们 append 到页面顶部的 sticky
div
时,它们会从 HTML 中的原始位置被破坏,无法替换当用户向上滚动时。
这是一个JSFiddle
如何将元素 append 到 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
标志用于避免多次追加
关于javascript - jQuery追加破坏原始元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26373315/