简体   繁体   中英

Hide older content in a div

HTML code is as follows -

<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. Now lines with class myLine are dynamically added. As you can notice overflow-y:auto is provided if content exceeds max-height:500px we will see scroll bar. What I want it to show latest 5 lines only. 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

//EDIT first gets hidden and new one gets appended

 $('.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.

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

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

}

You can automatically scroll the div (myDiv) to bottom.

So that last values will automatically be visible.

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

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

        });
        <script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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