嘿, 我是Mofei!
Getting Width and Height of Elements in JavaScript
Published December 18, 2012 at 08:24 PM

When writing a JavaScript screenshot feature, I wanted to get the width of a div that hasn't defined any CSS, so I used:

var a=document.getElementById('dom').style.width

To my surprise, the value I got was undefined... WHY??

I tried offsetWidth but found it wasn't the value I wanted. I suddenly remembered seeing something like computerStyle, so I searched on Baidu and finally understood why.

style                  // Can only get an element's inline styles; internal and external styles cannot be retrieved using style.
currentStyle         // Can compensate for the shortcomings of style, but it only applies to IE.
getComputedStyle     // Has the same function as currentStyle, but it applies to FF, Opera, Safari, and Chrome.

After research, I found I can use getComputedStyle to retrieve:

getStyle: function(element,attr){
     return (el.currentStyle ? el.currentStyle : getComputedStyle(el, null))[attr];
}
THE END
Previous
Is Google Coming Back? Google's Counterattack? 非诚勿扰 YouTube Advertising Promoting Google
Next
CSS cursor property example

More Great Articles

Got any insights on the content of this post? Let me know!

avatar

Mofei's Friend (Click to edit)

Don't be shy, just type away!
No comments yet
Be the first to comment!

HI. I AM MOFEI!

NICE TO MEET YOU!