2012-11-17 101 views
26

如何獲取元素的內部高度,而沒有填充和邊框?獲取元素的內部高度

沒有jQuery的,只是純粹的JS和一個跨瀏覽器的解決方案(包括IE7)

enter image description here

+1

爲什麼不能在CSS中使用'邊界box'?這樣你不必擔心這些事情......然後你可以使用'offsetHeight',它將返回沒有邊距的適當高度。 – elclanrs

+0

這是一個非常具體的問題,我製作了一個沒有CSS控制的插件,我只需要使用我得到的結果 – vsync

+0

所以...我猜你仍然可以設置「box-sizing:border-box」,它會爲你節省一些時間和頭痛。 – elclanrs

回答

30
var style = window.getComputedStyle(document.getElementById("Example"), null); 
style.getPropertyValue("height"); 

上述版本將在現代瀏覽器。請檢查currentStyle的IE瀏覽器。從評論

+5

你的意思是:'parseInt(style.getPropertyValue('height'));' – vsync

+4

如果css中沒有高度,那麼Internet Explorer將返回「auto」,所以你沒有它的高度! – Mic

+0

@Mic哪個Internet Explorer? – Fresheyeball

0

編輯:

http://jsfiddle.net/hTGCE/1/(更多的代碼,然後預期)

在你找到的功能,如上網本

function getRectangle(obj) { 

      var r = { top: 0, left: 0, width: 0, height: 0 }; 

      if(!obj) 
      return r; 

      else if(typeof obj == "string") 
      obj = document.getElementById(obj); 


      if(typeof obj != "object") 
      return r; 

      if(typeof obj.offsetTop != "undefined") { 

      r.height = parseInt(obj.offsetHeight); 
      r.width = parseInt(obj.offsetWidth); 
      r.left = r.top = 0; 

      while(obj && obj.tagName != "BODY") { 

       r.top += parseInt(obj.offsetTop); 
       r.left += parseInt(obj.offsetLeft); 

       obj = obj.offsetParent; 
      } 
      } 
      return r; 
     } 
如果你想減掉填充

/邊界寬度設置在CSS文件中,而不是動態屬性中的樣式屬性:

var elem = document.getElementById(id); 
    var borderWidth = 0; 

      try { 
      borderWidth = getComputedStyle(elem).getPropertyValue('border-top-width'); 

      } catch(e) { 

      borderWidth = elem.currentStyle.borderWidth; 
      } 
    borderWidth = parseInt(borderWidth.replace("px", ""), 10); 

和填充相同。然後你計算它。

+1

在互聯網上你可以找到各種垃圾代碼。我想爲這個神祕的最終答案,而不是一個臃腫,緩慢的代碼..但謝謝你的答案:) – vsync

+0

如果你有一個動態的高度沒有css屬性「高度」的元素與「getComputedStyle」的方法不會工作。或者我錯了? – Mic

+0

它確實有效,只是試了一下 – vsync

0

我有同樣的問題,發現沒有提供原生交叉plattform解決方案,但該方案易於雖然

var actual_h = element.offsetHeight; 

      if(parseInt(element.style.paddingTop.replace('px','')) > 0){ 
       actual_h=actual_h - parseInt(element.style.paddingTop.replace('px','')); 

      } 
      if(parseInt(element.style.paddingBottom.replace('px','')) > 0){ 
       actual_h=actual_h - parseInt(element.style.paddingBottom.replace('px','')); 

      } 
+1

請注意,因爲MDN [州](https://developer.mozilla。 org/en-US/docs/Web/API/HTMLElement/style#Getting_style_information),「style'屬性對於學習元素的風格沒有用處,因爲它只代表元素內聯'樣式「屬性[...]」。 – Spooky

+0

盒子大小在IE7中不起作用 – Chandrakant