Home  >  Article  >  Web Front-end  >  js method to get style

js method to get style

一个新手
一个新手Original
2017-10-19 10:36:431377browse


js gets 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>

1. How js gets style 1

Only inline styles can be obtained through style, for non-inline styles, then Unable to get

var box = document.getElementById(&#39;box&#39;);
console.log(box.style.width); // ""
console.log(box.style.height); // ""

2. js way to get style 2

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)

3. Compatible writing method, and remove the unit

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, &#39;width&#39;)); // 200
console.log(getStyle(box, &#39;border&#39;)); // 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn