关于css:css常用操作

获取元素宽高

1、只能获取内联款式

var ele = document.getElementById('element');
console.log(ele.style.width); // 空字符串
console.log(ele.style.height); // '100px'

2、可获取实时的style

MDN材料

var ele = document.getElementById('element');
console.log(window.getComputedStyle(ele).width); // '100px'
console.log(window.getComputedStyle(ele).height); // '100px'

3、Element.currentStyle.width/height

性能与第二点雷同,只存在于旧版本IE中(IE9以下),除了做旧版IE兼容,就不要用它了。

4、除了可能获取宽高,还能获取元素地位等信息

MDN材料

var ele = document.getElementById('element');
console.log(ele.getBoundingClientRect().width); // 100
console.log(ele.getBoundingClientRect().height); // 100

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理