尝试调用 HTMLElement.style 时背景简写属性的值错误地扩展
<p>在元素的样式中,我有一些内联 CSS 声明,包括背景的简写声明</p>
<pre class="brush:php;toolbar:false;"><style>
:root{
--bg-white: rgba(255, 255, 255, 0);
}
</style>
<div style="background: var(--bg-white); ... "></div></pre>
<p>但是当迭代 HTMLElement.style 时,速记属性看起来像是错误扩展的</p>
<pre class="brush:php;toolbar:false;">for (const declaration of Array.from(target.style)) {
const value = target.style.getPropertyValue(declaration)
console.log(`${declaration}: ${value}`)
}</pre>
<p>这应该根据 MDN 上的 HTMLElement.style 文档打印出 <code>background-color: var(--bg-white)</code> ,但我得到 <code>background-color: ''</code> </p>
<blockquote>
<p>扩展了简写属性。如果设置 style="border-top: 1px Solid black",则会设置普通属性(border-top-color、border-top-style 和 border-top-width)。</p>
</blockquote>
<p>有人遇到过这种情况吗?</p>
使用
Array.from(target.style)获取target.style的默认迭代器的问题。它不包括背景属性。根据规范,速记属性已扩展到其各个部分。一切都在代码中进行了解释。
感谢@t.niese 在评论中提供的提示。
<div id="test" style="background: var(--bg-white);">Test</div> <script> const target = document.querySelector('#test'); // style is itarable console.log(target.style[Symbol.iterator]); // but doesn't include background in the iterator console.log(...target.style); // but background is iterable! console.log(Object.getOwnPropertyDescriptor(target.style, 'background')); // we can see it in Object.keys console.log(Object.keys(target.style).filter(name => name === 'background')); // so we can iterate it anyway for(const k in target.style){ if(k === 'background'){ console.log(target.style[k]); } } // Object.entries works too console.log(Object.entries(target.style).filter(([name]) => name === 'background')); // or access directly console.log(target.style.getPropertyValue('background')); console.log(target.style.background); </script>如果您使用
HTMLElement.style,它将返回通过style属性直接应用(而不是计算)的内容。在这种情况下,浏览器无法知道
background: var(--bg-white);中的var(...)将解析什么并它将包含哪些background-...属性(变量的内容将放置在var(...)语句所在的位置,然后结果值将是已解析。所以如果你例如有
--bg-white: content-box Radial-gradient(crimson, skyblue);那么你的--bg-white实际上会影响多个属性。