angularjs 頁面自適應高度的方法
需求
在angularjs構建的業(yè)務系統(tǒng)中,通過ui-view路由實現(xiàn)頁面跳轉,初始化進入系統(tǒng)后,右側內容區(qū)域需要自適應瀏覽器高度。
實現(xiàn)方案
- 在ui-view所在的Div添加directive,directive中通過element.css初始化計算div的高度,動態(tài)更新div高度
- directive監(jiān)聽($$watch)angular的$digest,實時獲取body高度,動態(tài)賦值model或element.css改變
方案1:添加directive和element.css自適應高度
1.創(chuàng)建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.效果圖
原界面:右側區(qū)域的高度為自適應內容,導致下方存在黑色的背景色

調整后:右側區(qū)域的高度自適應瀏覽器

方案2:$watch監(jiān)聽body高度,賦值改變高度
1.創(chuàng)建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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Angular 根據 service 的狀態(tài)更新 directive
Angular JS (Angular.JS) 是一組用來開發(fā)Web頁面的框架、模板以及數(shù)據綁定和豐富UI組件。本文給大家介紹Angular 根據 service 的狀態(tài)更新 directive,需要的朋友一起學習吧2016-04-04

