获取元素宽高

获取元素宽高值

1.内联样式. element.style读取的只是元素内联样式,即写在元素的 style 属性上的样式,支持读写.

var elebox = document.getElementById('eleId');
var h = elebox.style.height;

外联样式、嵌套样式无法通过上述方法直接获取.

2.getComputedStyle (Chrome/ff)和currentStyle(ie)

var style = window.getComputedStyle ? window.getComputedStyle(elebox ,null) : null || elebox.currentStyle;
var h = style.height;

getComputedStyle 读取的样式是最终样式,包括了内联样式嵌入样式外部样式。只读不能写.

参数2不需要伪元素信息时,填null.

相同点

以上两种方法返回的都是 CSSStyleDeclaration 对象,返回的对象的键名是 css 的驼峰式写法.

3.cssRules(Chrome/ff)或rules(ie)

 var sheet = document.styleSheets[0];
 var rule = (sheet.cssRules || sheet.rules)[0];
 var h = rule.style.height;

最新的chrome都可以使用.

document.styleSheets 的返回对象是一个 styleSheetList ,是 styleSheet 对象的有序集合.

//获取元素的任意 CSS 属性值。
function getStyle(element, attr) {
   if(element.currentStyle) {
        return element.currentStyle[attr];
   } else {
        return getComputedStyle(element, false)[attr];
   }
}

4.clientHeight、scrollHeight、offsetHeight

通过上述三个属性获取数值,但是受其它参数影响.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值