页面加载(angularJS)时似乎无法滚动到div的底部

时间:2019-06-30 18:12:18

标签: javascript angularjs angularjs-ng-repeat mobile-angular-ui

我想在页面加载时滚动到div的底部,但是没有这样做。页面加载后,我便可以滚动。

CSS(隐藏的滚动条)

.scrollable {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.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;
}

HTML-使用init函数尝试在加载时滚动到底部

<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>&nbsp;&nbsp;{{message.message}}
         </div>
      </div>
   </div>   
</div>

控制器

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

}]);

1 个答案:

答案 0 :(得分:1)

在上述帮助下,我最终要做的是:

指令

//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

<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}}&nbsp;&nbsp;{{message.message}}</div>
       </div>
    </div>
</div>

CSS

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