检查窗口高度是否大于AngularJS中的div#content height

时间:2018-01-16 21:48:09

标签: javascript html css angularjs

如果window.height大于主要内容div的高度,我只想将css样式(position:fixed)添加到页脚。

在我的解决方案(下面)中,条件总是正确的,所以它不能像我期望的那样工作。此外,我不确定我是否使用$ scope。$ watch以正确的方式控制窗口高度 - 我不想每次更改页面时都按f5(例如,将主页改为联系页面)刷新范围并应用其他样式。

我找到了类似的主题(例如Forcing footer to bottom of page, if document height is smaller than window height)但没有找到AngularJS

我正在使用AngularJS 1.6。 这是我的代码:

controllersFooter.controller( 'footer' , [ '$scope' , '$window' , function( $scope , $window  ){

var $footer = angular.element(document.querySelector('#site-footer'));
$scope.windowHeight = jQuery( window ).height();

$window.onload = function() {

    $scope.$watch(function(){
        var contentHeight = document.getElementById('content-container').scrollHeight;
        return contentHeight;
    }, function(value){

        var contentHeight = value;

        if ( contentHeight < $scope.windowHeight ) {
            $footer.css(
            {
              "position":"fixed",
              "bottom":0,
              "left": 0,
              "right": 0
            }
          );
        }
    });

}; }]);

3 个答案:

答案 0 :(得分:0)

您可以在页脚中使用带有范围变量的ng-class,并根据页面的高度将其设置为true或false 更多关于ng-class https://docs.angularjs.org/api/ng/directive/ngClass

答案 1 :(得分:0)

1

请确保文档正文有滚动。

只是它可以是overflow: auto的任何其他div ...你希望它将是document.body,但这并不总是正确的

2

我建议您只使用滚动条订阅元素上的滚动事件,例如:

jQuery( elementWithScrollBar ).scroll(function() {
  $scope.fixed = calculateIfFooterIsFixed();
  $scope.$digest(); // run angular digest cycle to reflect scope changes to DOM,
                    // most likely you will need it
});

答案 2 :(得分:0)

Windows调整大小的事件本身可以在angularjs中使用。

angular.element($window).on('resize', this.onResize);

在你的情况下,例如......那样:

var footerHeight = document.getElementById('side-footer').scrollHeight;
this.onResize = function() {
    var contentHeight = document.getElementById('content-container').scrollHeight;
    $scope.$apply(function() {
        $scope.isFixed = contentHeight > $window.innerHeight - footerHeight
    });
}

并使用ng-class:

  <div id="side-footer" ng-class="{'fixed': isFixed}">

位置&#34;固定&#34;当主要内容小于可见窗口时: https://jsfiddle.net/UncleGoogle/jpy4zse9/25/ (由于某种原因,需要运行两次以正确设置小提琴脚尺寸)

相关问题