* {
margin: 0;
padding: 0;
}
.box {
width: 200px;
height: 100px;
margin: 100px;
padding: 50px;
border: 20px solid #33ff11;
background-color: #ff4343;
}<p id="box" class="box"></p>
通过style只能获取行内样式,对于非行内样式,则不能获取
var box = document.getElementById('box');
console.log(box.style.width); // ""
console.log(box.style.height); // ""window.getComputedStyle IE9以下不兼容 使用currentStyle
console.log(window.getComputedStyle(box, null)); // 返回的是对象CSSStyleDeclaration console.log(window.getComputedStyle(box, null).width); // 200px console.log(window.getComputedStyle(box, null).margin); // 100px console.log(window.getComputedStyle(box, null).backgroundColor); // rgb(255, 67, 67)
function getStyle(ele, attr) {
var val = null, reg = null;
if (window.getComputedStyle) {
val = window.getComputedStyle(ele, null)[attr];
} else {
val = ele.currentStyle[attr];
}
reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i; // 正则匹配单位
return reg.test(val) ? parseFloat(val) : val;
}
console.log(getStyle(box, 'width')); // 200
console.log(getStyle(box, 'border')); // 20px solid rgb(51, 255, 17)下载本文