2016-07-28 80 views
1

假設我在h1元素中有一個標題(任何元素都會這樣做)。它的內容是動態的(不知道標題的長度)。它應該顯示在一行中。 h1在DIV中(我們稱之爲容器)的大小有限。JavaScript,AngularJS:如何知道元素是否大於其容器?

如何知道元素(h1)溢出其容器(DIV)?

因此,如果它溢出,我會申請一個CSS類來處理這種情況。例如,我會將h1的隱藏內容滾動到視圖中。

  • 容器的寬度被定義爲相對於屏幕大小。

實施例:

#container { 
 
    width: 60%; 
 
    background-color: gray; 
 
    height: 50px; 
 
    // overflow: hidden; 
 
    position: relative; 
 
} 
 

 
h1 { 
 
    overflow: hidden; 
 
    height: 100%; 
 
    margin: 0; 
 
    line-height: 50px; 
 
}
<div id="container"> 
 
    <h1>a soft white or grey mineral consisting of hydrated calcium sulphate. It occurs chiefly in sedimentary deposits and is used to make plaster of Paris and fertilizers, and in the building industry.</h1> 
 
</div>

最佳的解決辦法是,如果它可以用於:初級在ngClass指令在ngIf,仲,但任何以下技術也都是良好: JavascriptAngularJSCSSAngularJS directive

+0

我不明白,所以你想要在容器中顯示h1的全部內容? – DirtyRedz

+0

最終是的,但我不想改變容器的大小,所以如果內容溢出,我想有條件地應用CSS類來滾動內容(h1)。問題是我不知道如何製作「條件」。 –

+0

你可以用純css來完成,只需將overflow:auto設置爲容器。它會檢測內部的內容是否溢出,只有當溢出時才添加滾動條。 –

回答

1

這是我在AngularJS directive解決方案。它不依賴父元素:

var myDirective = angular.module('myDirective', []); 
myDirective.directive('myDirective' , ['$timeout' , function($timeout) { 
    return { 
     link: function (scope , element , attrs) { 

      // Wait few milliseconds until element is re-rendered 
      // so that element properties reflect content size. 
      $timeout(function(){ 
       if (element[0].scrollWidth > element[0].offsetWidth){ 
        // overflow 
       } 
      }, 200); // $timeout 
     } // link 
    }; // return 
}]); // myDirective 

用例:

<h3 my-directive>Hello World!</h3> 

注:父元素必須有限制大小否則會調整的內容和元素將不會溢出。

1

假設jQuery你可以檢查元素的寬度。

if ($('h1').scrollWidth > $('#container').innerWidth()) { 
//overflown 

}

+0

目前'jquery'是我最不喜歡的,但讓我們拭目以待吧。謝謝你的努力! –

+0

+1顯示我的方向。順便說一句:我認爲這個情況更好:'element.scrollWidth> element.offsetWidth'。它不依賴於父元素。 –

相關問題