Javascript Can';在页面加载(angularJS)时,似乎无法滚动到div的底部
我想在页面加载时滚动到div的底部,但它没有这样做。我能够滚动页面加载后 CSS(隐藏滚动条) HTML-使用init函数尝试在加载时滚动到底部Javascript Can';在页面加载(angularJS)时,似乎无法滚动到div的底部,javascript,angularjs,angularjs-ng-repeat,mobile-angular-ui,Javascript,Angularjs,Angularjs Ng Repeat,Mobile Angular Ui,我想在页面加载时滚动到div的底部,但它没有这样做。我能够滚动页面加载后 CSS(隐藏滚动条) HTML-使用init函数尝试在加载时滚动到底部 <div class="scrollable" ng-controller="MatchDetailController as matchdetail" ng-init="init()"> <div class="scrollable-hidden-parent" > <div class="scr
<div class="scrollable" ng-controller="MatchDetailController as matchdetail"
ng-init="init()">
<div class="scrollable-hidden-parent" >
<div class="scrollable-hidden-child" id="scrollable-hidden">
<div ng-repeat="message in chats>
<b>{{message.name}}</b> {{message.message}}
</div>
</div>
</div>
</div>
在上面的帮助下,我终于做到了: 指示
//automatically scrolls to the bottom of the list on load
app.directive('scrollToBottom', function($timeout) {
return {
link: function(scope, element, attr) {
if (scope.$last === true) {
$timeout(function() {
var scroll_id = attr.scrollId;
var objDiv = document.getElementById(scroll_id);
objDiv.scrollTop = objDiv.scrollHeight;
}, 0);
}
}
};
});
HTML
ngInit
指令只有少数几种合适的用法,这不是其中之一。有关详细信息,请参阅。如果元素不是溢出的元素,则不会滚动。你在CSS中做什么使元素溢出?@georgeawg谢谢。我编辑了这篇文章,添加了mo细节和CSS。滚动工作,只是加载时不会滚动到底部。最可能的原因是ng repeat
指令。在函数获取scrollHeight
之前,浏览器没有将该指令添加到DOM中的
元素呈现出来。代码需要等待ng repeat
directve将元素添加到DOM和浏览器中以呈现新的DOM。在这种情况下,一个选项是生成一个执行滚动的指令,然后在链接
函数中包装在$timeout
中滚动的代码。这将确保在调用滚动的代码之前加载DOM。指令应位于带有ng if=“$last”
的ng repeat
内。
app.controller('MatchDetailController', ['$scope', '$http', '$location', '$rootScope', '$window', function MatchDetailController($scope,$http,$location,$rootScope, $window) {
$scope.init = function() {
var objDiv = document.getElementById("scrollable-hidden");
objDiv.scrollTop = objDiv.scrollHeight;
};
}]);
//automatically scrolls to the bottom of the list on load
app.directive('scrollToBottom', function($timeout) {
return {
link: function(scope, element, attr) {
if (scope.$last === true) {
$timeout(function() {
var scroll_id = attr.scrollId;
var objDiv = document.getElementById(scroll_id);
objDiv.scrollTop = objDiv.scrollHeight;
}, 0);
}
}
};
});
<div class="scrollable-hidden-parent">
<div class="scrollable-hidden-child" id="scrollable-hidden">
<div ng-repeat="message in chats" scroll-to-bottom scroll-id="scrollable-hidden">
<div>{{message.name}} {{message.message}}</div>
</div>
</div>
</div>
.scrollable-hidden-parent {
width: 100%;
height: 100%;
overflow: hidden;
}
.scrollable-hidden-child{
width: 100%;
height: 100%;
overflow-y: scroll;
padding-right: 17px;
box-sizing: content-box;
}