简体   繁体   中英

Can't seem to scroll to bottom of div on page load (angularJS)

I want scroll to the bottom of the div on page load but it's not doing it. I am able to scroll once the page loads.

CSS (hidden scroll bar)

.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 - uses the init function to attempt to scroll to bottom on load

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

Controller

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

}]);

With the help above, this is what I ended up doing:

Directive

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM