gpt4 book ai didi

javascript - 将内容添加到列表时保持滚动位置 (AngularJS)

转载 作者:数据小太阳 更新时间:2023-10-29 05:18:33 26 4
gpt4 key购买 nike

我一直在尝试使用 ng-repeat 将一些项目添加到可滚动容器内的列表中,最近的项目应该位于列表的顶部。如果在前置内容时容器的滚动条不在最顶部,我还需要保持滚动位置。

这是我的解决方案,但我仍然遇到问题。 Angular 在 dom 中渲染前置项目后总是闪烁。

var myApp = angular.module('myApp', []);

myApp.controller('MainCtrl', function($scope, $interval, $timeout) {
$scope.items = [];
$interval(function() {
var item = {
id: Math.random(),
text: (new Date()).toString()
};
$scope.items.unshift.apply($scope.items, [item]);

var $container = $('.stream-container');
var $topItem = $('.item:first');
var oScrollTop = $container.scrollTop();
var oOffset = $topItem.length ? $topItem.position().top : 0;

$timeout(function() {
// Executed after the dom has finished rendering
if ($container.scrollTop() !== 0) {
$container.scrollTop(oScrollTop + ($topItem.length ? $topItem.position().top : 0) - oOffset);
}
});
}, 1000);
});
.stream-container {
overflow-y: scroll;
overflow-x: none;
height: 100px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<body ng-app="myApp">
<div class="stream-container" ng-controller="MainCtrl">
<div class="stream">
<div class="item" ng-repeat="item in items track by item.id">{{ item.text }}</div>
</div>
</div>
</body>

最佳答案

我找到了 this post并将 $timeout 更改为 $scope.$$postDigest。现在它按预期工作。

var myApp = angular.module('myApp', []);

myApp.controller('MainCtrl', function($scope, $interval, $timeout) {
$scope.items = [];
$interval(function() {
var item = {
id: Math.random(),
text: (new Date()).toString()
};
$scope.items.unshift.apply($scope.items, [item]);

var $container = $('.stream-container');
var $topItem = $('.item:first');
var oScrollTop = $container.scrollTop();
var oOffset = $topItem.length ? $topItem.position().top : 0;

$scope.$$postDigest(function() {
// Executed after the dom has finished rendering
if ($container.scrollTop() !== 0) {
$container.scrollTop(oScrollTop + ($topItem.length ? $topItem.position().top : 0) - oOffset);
}
});
}, 1000);
});
.stream-container {
overflow-y: scroll;
overflow-x: none;
height: 100px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<body ng-app="myApp">
<div class="stream-container" ng-controller="MainCtrl">
<div class="stream">
<div class="item" ng-repeat="item in items track by item.id">{{ item.text }}</div>
</div>
</div>
</body>

关于javascript - 将内容添加到列表时保持滚动位置 (AngularJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32503265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com