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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Angularjs實現(xiàn)多個頁面共享數(shù)據(jù)的方式
本文給大家介紹使用Angularjs實現(xiàn)多個頁面共享數(shù)據(jù)的方式,通過定義一個共享服務service來實現(xiàn)此功能,對angularjs共享數(shù)據(jù)相關知識感興趣的朋友一起學習2016-03-03
angular ng-repeat數(shù)組中的數(shù)組實例
下面小編就為大家?guī)硪黄猘ngular ng-repeat數(shù)組中的數(shù)組實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
angular實現(xiàn)input輸入監(jiān)聽的示例
今天小編就為大家分享一篇angular實現(xiàn)input輸入監(jiān)聽的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Angular實現(xiàn)svg和png圖片下載實現(xiàn)
這篇文章主要介紹了Angular實現(xiàn)svg和png圖片下載實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-05-05

