因为之前用惯了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会有思维惯性,所以应该多学习