100px pops up in all browsers. Note that the width and height of the element defined in the style sheet can be obtained through getComputedStyle and currentStyle.
If the width and height of the element are not set in the style attribute or in the style sheet, can it still be obtained using getComputedStyle or currentStyle? The answer is that getComputedStyle can, but currentStyle cannot. As follows
test
<script> <br>function getStyle(el, name) { <br>if(window.getComputedStyle) { <br>return window.getComputedStyle(el, null); <br>}else{ <br>return el. currentStyle; <br>} <br>} <br>var div = document.getElementsByTagName('div')[0]; <br>alert(getStyle(div, 'width')); <br></script> ; <br>
</div> <br>div neither sets the style attribute nor introduces a style sheet. The width and height (browser default) can be obtained in Firefox/IE9/Safari/Chrome/Opera, but not in IE6/7/8, and auto is returned. <br>Note that the getStyle method here uses getComputedStyle first, and IE9 already supports this method. Therefore, the width and height can be obtained in IE9. However, IE6/7/8 does not support it and can only be obtained using currentStyle. <br>Scenario 3: The element neither sets the style attribute nor introduces a style sheet <br><div class="codetitle">
<span><a style="CURSOR: pointer" data="84427" class="copybut" id="copybut84427" onclick="doCopy('code84427')"><u>Copy the code </u></a></span> The code is as follows: </div>
<div class="codebody" id="code84427"> <br><div>test<div> <br><script> <br>function getStyle(el,name) { <br>if(window.getComputedStyle) { <br>return window.getComputedStyle(el, null)[name]; <br>}else{ <br>return el.currentStyle[name]; <br>} <br>} <br>function getWH(el, name) { <br>var val = name === "width" ? el.offsetWidth : el.offsetHeight, <br>which = name === "width" ? ['Left', 'Right'] : ['Top', 'Bottom']; <br>// display is none <br>if(val === 0) { <br>return 0; <br>} <br>for(var i = 0, a; a = which[i ];) { <br>val -= parseFloat( getStyle(el, "border" a "Width") ) || 0; <br>val -= parseFloat( getStyle(el, "padding" a) ) || 0; <br>} <br>return val 'px'; <br>} <br>var div = document.getElementsByTagName('div')[0]; <br>alert(getWH(div, 'width')); <br></script>
思路很简单:获取元素的offsetWidth/offsetHeight,减去元素的padding和border。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn