To Reset scroll position to newly added element

时间:2017-06-15 09:53:53

标签: javascript html angularjs

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>

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以在$("div#YourContentDiv p:last-child").offset()

中使用jquery animate函数

此外,Plunkr还有一个角度动画示例:

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

&#13;
&#13;
$("body, html").animate({ 
      scrollTop: $("div#YourContentDiv p:last-child").offset().top 
 }, 600);
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

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

//控制器

&#13;
&#13;
  $scope.add = function(item){

 $location.hash('scrollPosition'+item);
  $anchorScroll();
}
&#13;
&#13;
&#13;

上面的Angular锚点滚动解决了我的问题。

答案 3 :(得分:0)

这个肯定能解决你的问题。我已经为自己创建了这种方法。

请注意,这是根据滚动的数据表进行的。你需要根据你的代码更新像'.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;
    }
}