如何避免獲取復(fù)合值時(shí)瀏覽器之間差異
// 寫CSS的時(shí)候第一步初始化默認(rèn)樣式,避免瀏覽器之間的差異 ->
// 不僅如此,而且寫默認(rèn)樣式對(duì)于js以后獲取到的結(jié)果統(tǒng)一也是有幫助的
function getCSS(curEle, attr){
var val = null;
if("getComputedStyle" in window){
val=window.getComputedStyle(curEle,null)[attr];
}else{
val = curEle.currentStyle[attr];
}
return val;
}
// -> 標(biāo)準(zhǔn)瀏覽器和IE瀏覽器獲取的結(jié)果還是不一樣的 -> 對(duì)于部分樣式屬性,不同的瀏覽器獲取的結(jié)果不一樣,
// 主要是由于getComputedStyle和currentStyle在某些方面不一樣
console.log(getCss(box,"border")); // undefined
// 把復(fù)合值拆開來寫能避免這一問題
console.log(getCss(box,"borderTopWidth")); // 10px
第一次升級(jí): 把獲取到的樣式值"單位去掉"
function getCSS(curEle, attr){
var val = null;
if("getComputedStyle" in window){
val=window.getComputedStyle(curEle,null)[attr];
}else{
val = curEle.currentStyle[attr];
}
return parseFloat(val);
// -> 去單位這樣寫不行,對(duì)于某些樣式屬性的值是不能去單位的;
// -> 例如float, position, margin, padding, border的復(fù)合值等等...
}
console.log(getCss(box,"width"));
// 利用正則
function getCSS(curEle, attr){
var val = null, reg = null;
if("getComputedStyle" in window){
val=window.getComputedStyle(curEle,null)[attr];
}else{
val = curEle.currentStyle[attr];
}
reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i;
return reg.test(val) ? parseFlort(val) : val;
}
console.log(getCss(box,"width"));
第二次升級(jí): 有些樣式屬性在不同的瀏覽器中是不兼容的,例如: opacity
// opacity:0.1; 透明度, 在IE6~8中不兼容
// filter:alpha(opacity=10); 不兼容 使用濾鏡來處理;
function getCSS(curEle, attr){
var val = null, reg = null;
if("getComputedStyle" in window){
val=window.getComputedStyle(curEle,null)[attr];
}else{
// IE6~8;
// 如果傳遞進(jìn)來的結(jié)果是opacity, 說明要獲取的是透明度, 但是在IE6~8下獲取透明度需要使用filter
if(attr === "opacity"){
val = curEle.currentStyle["filter"]; // -> "alpha(opacity=10)"
// 把獲取到的結(jié)果進(jìn)行剖析,獲取里面的數(shù)字,讓數(shù)字除以100才和標(biāo)準(zhǔn)的瀏覽器保持一致
reg = /^alpha\(opacity=(\d+(?:\.\d+)?)\)$/i;
val = reg.test(val)?reg.exec(val)[1]/100:1;
}else{
val = curEle.currentStyle[attr];
}
}
reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i;
return reg.test(val) ? parseFlort(val) : val;
}
console.log(getCss(box,"opacity"));
補(bǔ)充: css偽類元素獲取
<style type="text/css">
#box{
width: 300px;
padding: 30px;
border: 1px dashed #ddd;
margin: 50px auto;
}
#box:before{
display: block;
content: "標(biāo)題";
background: lightgreen;
line-height: 1.5;
text-align: center;
}
#box:after{
display: block;
content: "結(jié)尾";
background: lightgreen;
line-height: 1.5;
text-align: center;
}
</style>
<div id="box">這是一段文字這是一段文字這是一段文字這是一段文字這是一段文字這是一段文字這是一段文字</div>
<script>
var box = document.getElementById("box")
console.log(window.getComputedStyle(box, "before").content)
console.log(window.getComputedStyle(box, "after").lineHeight)
</script>