mic*_*mia 6 javascript jquery dom scroll angularjs
我一直试图通过使用将一些项目添加到可滚动容器中的列表中ng-repeat,并且最近的项目应位于列表的顶部.如果在添加内容时容器的滚动条不在顶部,我还需要保持滚动位置.
这是我的解决方案,但我仍有问题.在角度为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);
});Run Code Online (Sandbox Code Playgroud)
.stream-container {
overflow-y: scroll;
overflow-x: none;
height: 100px;
position: relative;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
我发现这个职位,并改变$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);
});Run Code Online (Sandbox Code Playgroud)
.stream-container {
overflow-y: scroll;
overflow-x: none;
height: 100px;
position: relative;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1780 次 |
| 最近记录: |