简体   繁体   中英

To Reset scroll position to newly added element

In a container elements will be added and sorted dynamically. on clcik of add button i will add a new element to list. i want to set the scroll position to recently added element. Please help me out on this.

 <div ng-repeat="items in listItems | orderby" style="height:500px;overflow-y:auto"> <p id="scrollPosition{{items}}"> {{items}}</p> </div> 

When you add a new element just give it a unique ID as well and then simply use this javascript

location.href = "#";
location.href = "#myDiv";

You can use jquery animate function with $("div#YourContentDiv p:last-child").offset()

Also There is an angular animate example in Plunkr:

http://plnkr.co/edit/yz1EHB8ad3C59N6PzdCD?p=preview :

 $("body, html").animate({ scrollTop: $("div#YourContentDiv p:last-child").offset().top }, 600); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <div id="YourContentDiv"> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p>new text</p> <p style="color:red">new line</p> </div> 

<div ng-repeat="items in listItems | orderby" style="height:500px;overflow-y:auto"> 
<p id="scrollPosition{{items}}"> {{items}}</p>

//Controller

  $scope.add = function(item){ $location.hash('scrollPosition'+item); $anchorScroll(); } 

The above Angular anchor scroll resolves my issue.

This one will definitely solve your problem. I have created this methods for myself.

Please note that this is made according to datatables scrolling. you need to update classes like '.dataTables_scrollBody' according to your code.

var scrollPosition =0;
function saveScrollPosition ( container ) {
    if ( $( container ) != undefined && $( container ).find( '.dataTables_scrollBody' ) != undefined ) {
        scrollPosition = $( container ).find( '.dataTables_scrollBody' ).scrollTop();
    } else {
        scrollPosition = 0;
    }

}

function setScrollPosition ( container ) {
    if ( $( container ) != undefined && $( container ).find( '.dataTables_scrollBody' ) != undefined ) {
        $( container ).find( '.dataTables_scrollBody' ).scrollTop( scrollPosition );
    } else {
        scrollPosition = 0;
    }
}

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