js获取样式的方法

js教程评论428 views阅读模式

js获取样式

* {
    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. js获取样式的方式1

通过style只能获取行内样式,对于非行内样式,则不能获取

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

2. js获取样式的方式2

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)

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获取样式的方法的详细内容,更多请关注php教程其它相关文章!

企鹅博客
  • 本文由 发表于 2020年7月21日 05:54:51
  • 转载请务必保留本文链接:https://www.qieseo.com/393250.html

发表评论