繁体   English   中英

使用“ getComputedStyle”获取样式时,“ getPropertyPriority”不起作用

[英]'getPropertyPriority' doesn't work when getting styles with 'getComputedStyle'

我想获得一种dom风格以增加优先级。

“ CSSStyleDeclaration”具有“ getPropertyPriority”方法,并且其返回值存在问题。 在下面的示例中,当我获得“背景”时,它返回空,我想获得“重要”

用'styleSheets'获得的值是正常的,但是我不想使用循环来找到相应的选择器,我希望给我一个简单的解决方案。

这是文件链接

 // log is '', I want to get 'important' console.log(window.getComputedStyle(document.getElementById('box')).getPropertyPriority('background')); // log is 'important' console.log(document.styleSheets[0].cssRules[0].style.getPropertyPriority('background')); // log is 'important' console.log(document.getElementById('box').style.getPropertyPriority('width')); 
 #box { height: 100px; background: black !important; } 
 <div id="box" style="width: 100px !important;"></div> 

document.getElementById('box').styledocument.styleSheets[0].cssRules[0].style访问样式将直接按document.styleSheets[0].cssRules[0].style给出样式,而顾名思义执行getComputedStyle ,将始终给出渲染样式,即!important已删除,因此getPropertyPriority将始终给出'' 我认为没有选择,只能循环检查所有样式。

您可以像已经完成的一样检入样式表和样式属性:

 var arr = ['background', 'width', 'height']; arr.forEach(prop => { //console.log(window.getComputedStyle(document.getElementById('box')).getPropertyPriority(prop)); var isImportant = (document.styleSheets[0].cssRules[0].style.getPropertyPriority(prop) + document.getElementById('box').style.getPropertyPriority(prop)).length > 0; console.log({prop, isImportant}); }); 
 #box { height: 100px; background: black !important; } 
 <div id="box" style="width: 100px !important;"></div> 

由getComputedStyleStyle返回的CSSStyleDeclaration对象与从StyleSheet或Element的style属性获得的对象有所不同。

首先,该对象是只读的,不能在其上使用setProperty

 const comp = getComputedStyle(test); comp.setProperty('backgroundColor', 'green'); 
 <div id="test" style="height:25px;background-color:red"></div> 

然后,在获取其属性时,将返回该属性的计算值,该值与已编写的值不同:

 const comp = getComputedStyle(test); console.log('computed', comp.getPropertyValue('width')); const auth = test.style; console.log('from style', auth.getPropertyValue('width')); 
 <div id="test" style="width:calc(3% + 25px)"></div> 

并且由于此CSSStyleDeclaration字典仅包含计算出的属性,因此不需要任何重要性,因为这些属性将始终是单独的,因此getPropertyPriority将始终返回空字符串。

要检索设置此属性的原始规则通常是不可能的,它很可能来自您无法读取的跨域StyleSheet。 而且,即使传入的CSSTypedOM确实为我们提供了检索创作单位和值的手段,也没有暴露出属性的重要性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM