[英]Assigning a subset of properties with the Object.assign() method
我正在开发 chrome 扩展,并且正在使用iframe
元素创建侧面板。 我有一个 object 存储 styles 对应的iframe
:
const sidePanelStyle = {
background: 'white',
// some other vars
};
我创建iframe
并分配我的设置:
let sidePanel = document.createElement('iframe');
Object.assign(sidePanel.style, sidePanelStyle);
一切正常,但在我之前
sidePanel.style = Object.assign(sidePanel.style, sidePanelStyle);
它没有将任何东西合并到sidePanel.style
(我希望.assign()
根据MDN返回合并的 object)。
我是 JS 新手,所以问题是:
Object.assign()
我到底缺少什么? 虽然返回合并的 object 是多余的( .assign()
方法将所有内容合并到第一个参数中),但当返回 object 时,我仍然很好奇为什么它不起作用。
const sidePanelStyle = { background: 'gray', height: '100%', padding: '20px', width: '400px', position: 'fixed', top: '0px', right: '0px', zIndex: '9000000000000000000', }; let sidePanel = document.createElement('iframe'); // this works fine // Object.assign(sidePanel.style, sidePanelStyle); // this doesn't sidePanel.style = Object.assign(sidePanel.style, sidePanelStyle); document.body.appendChild(sidePanel);
这是 DOM 元素的style
属性的一个怪癖,不幸的是回到了 web 浏览器的早期阶段,其中添加了一些东西......不管用什么非常非常奇怪的语义。
当您读取元素的style
属性时,您会得到一个 object,它具有内联 styles 的属性。 但是当你写它时,你写的东西被视为一个字符串或null
。 (虽然正式,它应该是只读的。不过,在今天的浏览器中,它并没有被这样对待。)
故事的寓意:不要给它写信(除非你写null
来完全清除它)。
所以当你这样做时:
sidePanel.style = Object.assign(sidePanel.style, sidePanelStyle);
...发生的是:
styles 已成功添加到sidePanel.style
,因为Object.assign
写入其第一个参数中给出的 object,然后
它返回的 object (也是sidePanel.style
)被转换为字符串并解释为样式属性。 (虽然,同样,它应该是只读的。)
但是当你将其转换为字符串时,得到的字符串是"[object CSSStyleDeclaration]"
,不能转换为 styles,所以你将元素上的 styles 擦掉。
这是一个更简单的演示:
const example = document.getElementById("example"); example.style.color = "blue"; setTimeout(function() { console.log("example.style.color before: " + example.style.color); // Assigning it to itself, which is effectively what // your code with `Object.assign` was doing example.style = example.style; console.log("example.style.color after: " + example.style.color); console.log("String(example.style): " + String(example.style)); }, 800);
<div id="example">This is the example div</div>
如您所见,无论如何都没有理由回写它,因为属性已添加到其中,因为它是Object.assign
的第一个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.