我目前正在学习 TypeScript,但我不知道如何正确解决这个问题。我想对作为样式函数参数给出的 HTMLElement 进行样式设置,如下所示:
function styleElement(unstyled: HTMLElement) {
const styled = unstyled.cloneNode(); // styleElement should be a pure function
styled.style = { opacity: 0 }; // TypeScript says: Property 'style' does not exist on type 'Node'.
return styled;
}
我已经检查了“Node”接口(interface)声明,并且样式属性丢失。据我所知,W3C 规范中描述了 Node 没有任何样式属性。但是我该如何解决这个限制的问题呢?
然而,覆盖“HTMLElement”上的样式属性会触发只读错误,这也很奇怪。
谢谢!
最佳答案
您可以转换:
function styleElement(unstyled: HTMLElement) {
const styled = unstyled.cloneNode() <strong>as HTMLElement</strong>;
styled.style.opacity = 0 // Now works properly.
// You can't reassign HTMLElement#style, that won't work.
return styled;
}
关于javascript - 将样式应用于 TypeScript 节点元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45029685/