首頁 > web前端 > js教程 > 主體

angularjs中如何實作頁面自適應?

亚连
發布: 2018-06-11 16:18:37
原創
2427 人瀏覽過

本篇文章主要介紹了angularjs 頁面自適應高度的方法,現在分享給大家,也給大家做個參考。

需求

在angularjs建構的業務系統中,透過ui-view路由實現頁面跳轉,初始化進入系統後,右側內容區域需要自適應瀏覽器高度。

實作方案

  1. 在ui-view所在的p添加directive,directive中透過element.css初始化計算p的高度,動態更新p高度

  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.p元素新增directive

<p ui-view auto-height></p>
登入後複製

3 .效果圖

原始介面:右側區域的高度為自適應內容,導致下方存在黑色的背景色

調整後:右側區域的高度自適應瀏覽器

方案2:$watch監聽body高度,賦值改變高度

1.創建resize directive

var app = angular.module(&#39;miniapp&#39;, []);

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

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

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

    }, true);

    w.bind(&#39;resize&#39;, function () {
      scope.$apply();
    });
  }
})
登入後複製

2.在p元素上增加resize directive

<p ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>
  window.height: {{windowHeight}} <br />
  window.width: {{windowWidth}} <br />
</p>
登入後複製

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

使用jquery css3如何實作熊貓tv導航

在jQuery如何實作定時隱藏對話框

詳細解讀vue-admin與後端(flask)分離結合

#在Vue中設定背景圖片

############# ##使用vue less如何實作簡單換膚功能############使用angular、react和vue如何實作相同的面試題元件######

以上是angularjs中如何實作頁面自適應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!