Home > Web Front-end > JS Tutorial > body text

js method to get style

一个新手
Release: 2017-10-19 10:36:43
Original
1385 people have browsed it


js gets style

* {
    margin: 0;
    padding: 0;
}
.box {
    width: 200px;
    height: 100px;
    margin: 100px;
    padding: 50px;
    border: 20px solid #33ff11;
    background-color: #ff4343;
}
Copy after login
<p id="box" class="box"></p>
Copy after login

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); // ""
Copy after login

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)
Copy after login

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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template