javascript获取元素的offsetWidth/offsetHeight方法
网页特效获取元素的offsetWidth/offsetHeight方法
思路很简单:获取元素的offsetWidth/offsetHeight,减去元素的padding和border
元素通过引入样式表设置width/height
有两种方式引入样式表,一是使用link标签引入单独的css教程文件,二是直接在html页面中使用style标签。这里使用第二种方式测试
<style>
div {width: 100px}
</style>
<div>test<div>
<script>
function getStyle(el, name) {
if(window.getComputedStyle) {
return window.getComputedStyle(el, null);
}else{
return el.currentStyle;
}
}
var div = document.getElementsByTagName('div')[0];
alert(getStyle(div, 'width'));
</script>
所有浏览器中均弹出了100px。说明通过getComputedStyle和currentStyle可以获取到元素被定义在样式表中的宽高。
那如果元素即没有在style属性中设置宽高,也没有在样式表中设置宽高,还能用getComputedStyle或currentStyle获取吗?答案是getComputedStyle可以,currentStyle不可以。如下
<div>test<div>
<script>
function getStyle(el, name) {
if(window.getComputedStyle) {
return window.getComputedStyle(el, null);
}else{
return el.currentStyle;
}
}
var div = document.getElementsByTagName('div')[0];
alert(getStyle(div, 'width'));
</script>
div 既没有设置style属性,也没有引入样式表。在Firefox/IE9/Safari/Chrome/Opera中可以获取到宽高(浏览器默认),但IE6/7/8中却不行,返回的是auto。
注意,这里getStyle方法优先使用getComputedStyle,而IE9已经支持该方法。因此IE9中可以获取到宽高。但IE6/7/8不支持,只能使用currentStyle获取
<div>test<div>
<script>
function getStyle(el) {
if(window.getComputedStyle) {
return window.getComputedStyle(el, null);
}else{
return el.currentStyle;
}
}
function getWH(el, name) {
var val = name === "width" ? el.offsetWidth : el.offsetHeight,
which = name === "width" ? ['left', 'right'] : ['top', 'bottom'];
// display is none
if(val === 0) {
return 0;
}for(var i = 0, a; a = which[i++];) {
val -= parseFloat( getStyle(el, "border" + a + "Width") ) || 0;
val -= parseFloat( getStyle(el, "padding" + a) ) || 0;
}
return val + 'px';
}
var div = document.getElementsByTagName('div')[0];
alert(getWH(div, 'width'));
</script>
补充:网页制作,js教程