2013-02-14 149 views
2
尺寸

我正在尋找從Javascript找到以下計算尺寸的固體,跨瀏覽器的方式:查找HTML元素像素從Javascript

  • 內容矩形:最裏面的內容區域
  • 客戶矩形:內容區域+填充
  • 完整的矩形:內容+填充+邊框+緣

它不必是正是分組,我只是在尋找足夠的信息來併發症把任何一個盒子分解成content-> padding-> border-> margin分段。

(我可能不會去關心滾動條,但如果他們有一個良好定義的行爲,以及,我不會介意知道)

我希望能夠得到這些作爲像素值值,無論它們是如何從CSS進行樣式設置的。所以即使在例如margin-left: autowidth: 50%,我想能夠提取像素計算結果。

請不要jQuery解決方案,我正在尋找vanilla Javascript + DOM的答案。

+0

你設法解決這個問題嗎? – 2015-02-21 05:33:38

回答

0

這樣做的jQuery方法是調用.outerWidth()或.outerHeight()。在無法使用jQuery的情況下,您可以查看jQuery source以瞭解它們是如何實現這一點的。

或者,這裏有幾個答案可以產生相同的結果。例如:what is the jQuery outerHeight() equivalent in YUI & outerWidth without jquery。分別

document.getElementById('container').offsetWidth; // "Outer" Width 
document.getElementById('container').clientWidth; // "Inner" Width 

隨着.offsetHeight和.clientHeight爲高度,:

從後者。

+0

使用'$('#elementId')。innerHeight()'和'$('#elementId')。innerWidth()'作爲內容寬度。 – Rembunator 2013-02-14 14:14:43

+1

實際上,innerWidth()和outerWidth()都包含填充,而outerWidth()也包含邊框和可選的邊距。 坦率地說,我希望我不必篩選整個jQuery源代碼來找到這些答案;肯定有其他人必須做到這一點沒有jQuery? – tbone 2013-02-14 14:17:41

0

這可能會幫助:

<style> 
    body { 
    margin: 10%; 
    padding:10px 0 0; 
    border:1px solid #000; 
    } 
</style> 

var elem = document.body; 

var computedStyle = window.getComputedStyle ? getComputedStyle(elem, '') : elem.currentStyle; 

var marginTop = computedStyle.marginTop; 
var borderTop = computedStyle.borderTopWidth; 
var paddingTop = computedStyle.paddingTop; 
console.log(marginTop); 
console.log(borderTop); 
console.log(paddingTop); 

//爲

我返回168px,1px的,10px的

但它返回百分比爲IE < 9.對於老版本,你應該變換百分比像素(可以在這裏找到更多http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

+0

看起來像你在這裏的東西......當我重新審視這個問題時,我會放棄這一點。 – tbone 2013-08-25 22:20:45