javascript - jQuery追加破坏原始元素

标签 javascript jquery html css append

我的网页顶部有一个 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/

相关文章:

javascript - 如何为 Jest 初始化 Feathers 实例一次

html - css "li:hover ul"top value/line-height 依赖计算

javascript - 客户端 JavaScript 字段验证

javascript - 从 HTML 表单中获取值

jquery - 当我们使用 tr :odd 时如何在 tr 中给出悬停效果

javascript - 如何模拟输入键只需单击按钮?

javascript - 将航路点添加到 Google 距离矩阵以确定里程

javascript - 如何根据其他客户端的事件更新异步页面?

javascript - 使用angularJS单击时更改目标属性

javascript - 拖放,防止尴尬的突出显示?