当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > angularjs 页面自适应高度的方法

angularjs 页面自适应高度的方法

2018年01月26日  | 移动技术网IT编程  | 我要评论

神奇宝贝dp76,妞妞淘,黄州房屋出租

需求

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网