js获取css属性值

因为之前用惯了jq来获取和设置css属性,然后在做demo不使用jq的情况下,竟然在这一点上碰到了问题,然后就自个搜了搜为什么,在查看了很多文档和博客之后才终于搞明白了。

<style>
.box{
    width:200px;
    height:200px;
    border:1px solid red;
    text-align: center;
}
</style>
<div class="box" style="line-height:150px">
   居中
</div>
jquery方法

我们在用jq获取id为box的css属性的时候是最简单的

//jquery方法
const jq_width = $('.box').css('width');
const jq_lineHeight = $('.box').css('line-height');
console.log(jq_width,jq_lineHeight);//200px 150px

这种方式应该是最简洁明了的吧。

然后我们再用js原生方法去获取

// 原生style.css方法
const box = document.querySelector('.box');
const js_width = box.style.width;
const js_lineHeight = box.style.lineHeight;
console.log(js_width,js_lineHeight);//   150px

在这里我们会发现style.css方法只能获取到写在标签上的属性 style = "line-height:150px" 不能获取写在<style>``</style>中的css属性

然后在网上查了很多资料才知道下面这个东西:

window.getComputedStyle

使用window.getComputedStyle这个方法获取所有经过浏览器计算过的样式
window.getComputedStyle(当前要操作的元素对象,当前元素的伪类[一般我们不用伪类写null])

const js_style = window.getComputedStyle(box,null);
console.log(js_style);//所有样式
const js_lineHeightStyle = window.getComputedStyle(box,null).lineHeight;
console.log(js_lineHeightStyle);//150px

// 在ie6~8下不兼容,因为window下没有getComputedStyle这个属性
//在ie6~8下可以使用currentStyle来获取所有经过浏览器计算过的样式

const js_currentStyle = box.currentStyle;
console.log(js_currentStyle);//火狐和谷歌为Undefined,IE返回CSS对象

这里写两个简单的获取css属性值的方法(基于原生)

//第一版
function getCss(element, attr){
    if(element.currentStyle){
        return element.currentStyle[attr];
    }else{
        return window.getComputedStyle(element,null)[attr];
    }
}
//推荐第二版
//这个是直接获取值
function getCss(curEle,attr){  
    var val = null,reg = null;  
    if("getComputedStyle" in window){  
        val = window.getComputedStyle(curEle,null)[attr];  
    } else {   //ie6~8不支持上面属性  
        //不兼容  
        if(attr === "opacity"){  
            val = curEle.currentStyle["filter"];   //'alpha(opacity=12,345)'  
            reg = /^alphaopacity=(\d+(?:\.\d+)?)opacity=(\d+(?:\.\d+)?)$/i;  
            val = reg.test(val)?reg.exec(val)[1]/100:1;  
        } else {  
            val = curEle.currentStyle[attr];  
        }  
    }  
    reg = /^(-?\d+(\.\d)?)(px|pt|em|rem)?$/i;  
    return reg.test(val)?parseFloat(val):val;   
}
console.log(getCss(box,'width'));//200

好了,用惯了jquery会有思维惯性,所以应该多学习

  • 10
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值