P粉4133078452023-09-04 20:05:48
Problem using Array.from(target.style)
to obtain the default iterator of target.style
. It does not include background properties. According to the specification, shorthand properties have been extended to its various parts.
Everything is explained in the code.
Thanks to @t.niese for the tip in the comments.
<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>
P粉4364105862023-09-04 17:12:59
If you use HTMLElement.style
, it will return what is applied directly (rather than calculated) via the style
attribute.
In this case, the browser has no way of knowing what the var(...)
in background: var(--bg-white); will parse and will Which
background-... properties are included (the contents of the variable will be placed where the
var(...) statement is and the resulting value will be parsed.
--bg-white: content-box Radial-gradient(crimson, skyblue); then your
--bg-white will actually affect Multiple properties.