一、获取元素的行内样式
var obj = document.getElementById("test");
alert(obj.height + "\n" + obj.width);
// 200px 200px typeof=string
只是将style属性中的值显示出来
二、获取计算后的样式
var obj = document.getElementById("test");
var style = null;
if (window.getComputedStyle) {
style = window.getComputedStyle(obj, null); // 非IE
} else {
style = obj.currentStyle(null); // IE
}
alert("width=" + style.width + "\nheight=" + style.height);
注意:如果不设置元素的宽度和高度,那么在非IE浏览器下返回默认的宽度和高度。在IE下面返回auto字符串
三、获取<link>和<style>标签写入的样式
var obj = document.styleSheets[0]; // [object StyleSheetList] 样式表的个数<link>var rule = null;// [object CSSRule]
if (obj.cssRules){
rule = obj.cssRules[0]; // 非IE [object CSSRuleList]
} else {
rule = obj.rules[0]; // IE [object CSSRuleList]
}
alert(rule.style.width);
cssRules(或rules)只能获取到内联和链接样式的宽和高,不能获取到行内和计算后的样式。
总结:
以上的三种CSS获取元素大小的方法,只能获取元素的CSS大小,却无法获取元素本身实际的大小。比如加上了内边距、滚动条、边框之类的。
网友评论