获取元素的最终样式
看到这样一道微信面试题:用JS代码求出页面上一个元素的最终的background-color,不考虑IE浏览器,不考虑元素float情况。(2017.3.1补充:赛赛同学提醒了我,还要考虑background这个复合属性,情况变得异常复杂了,以下代码是之前的,没有考虑。)
由于element.style.cssText只能访问到元素内联样式即标签style属性,只能用document.defaultView.getComputedStyle,考虑IE的话可用element.currentStyle,不过element.currentStyle无法用于伪元素而document.defaultView.getComputedStyle可以。如果要考虑元素不可见或者没有设定值的时候,backgroundColor的表现可以认为是其父元素的表现(题目的“不考虑元素float情况”)也是这个意思吧。让我来写写代码:
/***获取元素自身css属性*@paramelem元素*@paramproperty属性名(这里不考虑float)*@returns{string}css属性值*/functioncomputedStyle(elem,property){if(!elem||!property){return'';}varstyle='';if(elem.currentStyle){style=elem.currentStyle[camelize(property)];}elseif(document.defaultView.getComputedStyle){style=document.defaultView.getComputedStyle(elem,null).getPropertyValue(property);}returnstyle;}/***将-连接属性名转换为驼峰命名形式*@param{string}str-连接字符串*@returns{string}驼峰命名字符串*/functioncamelize(str){returnstr.replace(/-(\w)/g,function(s,p1){returnp1.toUpperCase();});}/***在elem获取的背景色是否为最终的背景色*@paramelem*@returns{boolean}*/functionisFinalBGColor(elem){varbgc=computedStyle(elem,'background-color');return(!!bgc)&&(bgc!=='transparent')&&(bgc!=='rgba(0,0,0,0)')&&(computedStyle(elem,'opacity')!=='0')&&(computedStyle(elem,'visibility')!=='hidden')&&(computedStyle(elem,'display')!=='none');}/***获得元素最终的背景色(不考虑半透明叠加颜色的情况)*@paramelem*@returns{string}*/functiongetFinalBGColor(elem){if(isFinalBGColor(elem)){returncomputedStyle(elem,'background-color');}elseif(elem!==document.documentElement){returngetFinalBGColor(elem.parentNode);}return'';}
经过测试,在通常情况下,以上代码可用。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。