jQuery附加破坏原始元素

时间:2014-10-15 02:02:47

标签: javascript jquery html css append

我的网页顶部有div我希望在用户向下滚动时附加内容。

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

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

这是JSFiddle

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

2 个答案:

答案 0 :(得分:0)

你需要克隆并附加其他它就像将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();
        }
    });
});
&#13;
.sticky {
    position: fixed;
    top:0;
    z-index: 100;
}
&#13;
<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>
&#13;
&#13;
&#13;

sticky标志用于避免多个附加

答案 1 :(得分:0)

请参阅http://jsfiddle.net/wfrxujst/2/

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

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

滚动显示隐藏的项目:

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