angularjs 页面自适应高度

需求

在angularjs构建的业务系统中,通过ui-view路由实现页面跳转,初始化进入系统后,右侧内容区域需要自适应浏览器高度


实现方案

  1. 在ui-view所在的Div添加directive,directive中通过element.css初始化计算div的高度,动态更新div高度

  2. directive监听($$watch)angular的$digest,实时获取body高度,动态赋值model或element.css改变

方案1:添加directive和element.css自适应高度

1.创建directive

define([ "app" ], function(app) {
    app.directive('autoHeight',function ($window) {
        return {
            restrict : 'A',
            scope : {},
            link : function($scope, element, attrs) {
                var winowHeight = $window.innerHeight; //获取窗口高度
                var headerHeight = 80;
                var footerHeight = 20;
                element.css('min-height',
                        (winowHeight - headerHeight - footerHeight) + 'px');
            }
        };
    });
    return app;
});

1.div元素添加directive

<div ui-view auto-height></div>

3.效果图
原界面:右侧区域的高度为自适应内容,导致下方存在黑色的背景色
这里写图片描述

调整后:右侧区域的高度自适应浏览器
这里写图片描述

方案2:$watch监听body高度,赋值改变高度

1.创建resize directive

var app = angular.module('miniapp', []);

function AppController($scope) {
    /* Logic goes here */
}

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        scope.getWindowDimensions = function () {
            return { 'h': w.height(), 'w': w.width() };
        };
        scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;

            scope.style = function () {
                return { 
                    'height': (newValue.h - 100) + 'px',
                    'width': (newValue.w - 100) + 'px' 
                };
            };

        }, true);

        w.bind('resize', function () {
            scope.$apply();
        });
    }
})

2.在div元素上增加resize directive

<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>
    window.height: {{windowHeight}} <br />
    window.width: {{windowWidth}} <br />
</div>

参考资料

  1. http://stackoverflow.com/questions/14703517/angular-js-set-element-height-on-page-load
  2. http://nahidulkibria.blogspot.com/2014/10/angullarjs-directive-to-watch-window.html
  3. https://coderwall.com/p/7-acga/simple-angularjs-directive-to-match-window-height
  4. http://m.blog.csdn.net/article/details?id=47252279
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值