jsノート五十三の取得要素スタイル情報(2)

3176 ワード

複合値の取得時のブラウザ間の差異を回避する方法
//  CSS             ,           -> 
//     ,         js                

function getCSS(curEle, attr){
    var val = null;
    if("getComputedStyle" in window){
        val=window.getComputedStyle(curEle,null)[attr];
    }else{
        val = curEle.currentStyle[attr];
    }
    return val;
}
// ->       IE               ->         ,              ,
//      getComputedStyle currentStyle        
console.log(getCss(box,"border")); // undefined
//                  
console.log(getCss(box,"borderTopWidth")); // 10px

最初のアップグレード:取得したスタイル値を「単位を削除」
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); 
    // ->         ,                 ;
    // ->   float, position, margin, padding, border      ...
}
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"));

2回目のアップグレード:いくつかのスタイルプロパティは、異なるブラウザで互換性がありません.たとえば、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;
        //           opacity,           ,    IE6~8          filter
        if(attr === "opacity"){
            val = curEle.currentStyle["filter"]; // -> "alpha(opacity=10)"
            //            ,       ,     100            
            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"));

補足:css擬似クラス要素取得

var box = document.getElementById("box") console.log(window.getComputedStyle(box, "before").content) console.log(window.getComputedStyle(box, "after").lineHeight)