简体   繁体   English

将滚动位置重置为新添加的元素

[英]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 当您添加新元素时,只需为其指定一个唯一的ID,然后只需使用此javascript

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

You can use jquery animate function with $("div#YourContentDiv p:last-child").offset() 您可以将jquery动画功能与$("div#YourContentDiv p:last-child").offset()

Also There is an angular animate example in Plunkr: 在Plunkr中也有一个角度动画示例:

http://plnkr.co/edit/yz1EHB8ad3C59N6PzdCD?p=preview : 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. 上面的Angular锚滚动解决了我的问题。

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. 您需要根据您的代码更新“ .dataTables_scrollBody”之类的类。

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;
    }
}

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

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