Home > Article > Web Front-end > js method to get style
* { 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>
Only inline styles can be obtained through style, for non-inline styles, then Unable to get
var box = document.getElementById('box'); console.log(box.style.width); // "" console.log(box.style.height); // ""
window.getComputedStyle Incompatible with IE9 and below, use 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)
The above is the detailed content of js method to get style. For more information, please follow other related articles on the PHP Chinese website!