<p id="box" class="box"></p>
1. js获取样式的方式1通过style只能获取行内样式,对于非行内样式,则不能获取
var box = document.getelementbyid('box'); console.log(box.style.width); // "" console.log(box.style.height); // ""
2. js获取样式的方式2window.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)
3. 兼容写法,并去掉单位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)
以上就是js获取样式的方法的详细内容。
