简体   繁体   English

隐藏div中的旧内容

[英]Hide older content in a div

HTML code is as follows - HTML代码如下-

<div id="myDiv" style="max-height:500px; overflow-y:auto;margin-top: 15px" >
    <div id="myInnerDiv" style="display:none;border:1px solid black;">
        <span class='myLine' >data1</span>
        <span class='myLine' >data2</span>
        <span class='myLine' >data3</span>
        <span class='myLine' >data4</span>
        <span class='myLine' >data5</span>
    </div>
</div>

visibility of myInnerDiv is controller depending on the content. myInnerDiv可见性取决于内容,取决于控制器。 Now lines with class myLine are dynamically added. 现在将动态添加具有myLine类的行。 As you can notice overflow-y:auto is provided if content exceeds max-height:500px we will see scroll bar. 如您所见,如果内容超过max-height:500px ,则会提供overflow-y:auto我们将看到滚动条。 What I want it to show latest 5 lines only. 我想要它仅显示最新的5行。 So if we add 所以如果我们加上

<span class='myLine' >data5</span>

then 然后

<span class='myLine' >data1</span>

should be removed or hidden. 应该删除或隐藏。 Any suggestions? 有什么建议么?

You could use something like this. 您可以使用类似这样的东西。 With this solution you don't lose your content from "older" lines. 使用此解决方案,您不会因“较旧”的行而丢失内容。

and you should probably use div instead of span since span has display: inline-block as standard and therefore won't give you a new line 并且您可能应该使用div而不是span因为span已display: inline-block作为标准,因此不会给您换行

//EDIT first gets hidden and new one gets appended //首先将EDIT隐藏起来,然后附加新的

 $('.addLine').click(function(){ $('#myInnerDiv').append('<div class="myLine">test</div>'); if($('#myInnerDiv').find('.myLine').length > 5) { $('#myInnerDiv').find('.myLine').not('.hidden').first().addClass('hidden'); } }); 
 .hidden { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myDiv" style="max-height:500px; overflow-y:auto;margin-top: 15px" > <div id="myInnerDiv" style="display:block;border:1px solid black;"> <div class='myLine' >data1</div> <div class='myLine' >data2</div> <div class='myLine' >data3</div> <div class='myLine' >data4</div> <div class='myLine' >data5</div> </div> </div> <div class="addLine">add Line </div> 

if($('.myLine').length() > 5 ) {

  $('.myLine').first().remove();

}

something like that. 这样的事情。 or you could add a new class to the .first() and have it hidden. 或者您可以将一个新类添加到.first()并将其隐藏。

if($('.myLine').length() > 5 ) {

  $('.myLine').first().replaceWith(yourData);

}

You can automatically scroll the div (myDiv) to bottom. 您可以自动将div(myDiv)滚动到底部。

So that last values will automatically be visible. 这样最后的值将自动可见。

        <script>
        $(document).ready(function(){

            var objDiv = $('$myDiv');
            objDiv.scrollTop = objDiv.scrollHeight;

        });
        <script>

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

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