当前位置:Gxlcms > JavaScript > JavaScript获取元素尺寸和大小操作总结_javascript技巧

JavaScript获取元素尺寸和大小操作总结_javascript技巧

时间:2021-07-01 10:21:17 帮助过:6人阅读

一、获取元素的行内样式

代码如下:

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; // IE
}
alert("width=" + style.width + "\nheight=" + style.height);

注意:如果不设置元素的宽度和高度,那么在非IE浏览器下返回默认的宽度和高度。在IE下面返回auto字符串

三、获取和