gpt4 book ai didi

css - 影子 dom 样式不显示

转载 作者:行者123 更新时间:2023-11-28 14:23:41 27 4
gpt4 key购买 nike

通过此实例化的 Web 组件样式不正确:

connectedCallback() {
const shadowRoot = this.attachShadow({ mode: 'open' });
this.svg = document.createElement('svg');
this.svg.style = `
height: 80px;
width: 80px;
background-color: beige;
`;
shadowRoot.appendChild(this.svg);
}

但是,style 属性在 Chrome DevTools 中显示了正确的数据。如果我以这种方式重写逻辑,样式就会出现。

connectedCallback() {
const shadowRoot = this.attachShadow({ mode: 'open' });
let htmlHolder = document.createElement('template');
htmlHolder.innerHTML = `<svg></svg>`;
shadowRoot.appendChild(htmlHolder.content.cloneNode(true));
this.svg = shadowRoot.querySelector('svg');
this.svg.style = `
height: 80px;
width: 80px;
background-color: beige;
`;
}

我不确定为什么这两个行为不同。

最佳答案

如果您使用 createElement 定义 SVG 元素,您应该设置特定的 SVG 命名空间,即 http://www.w3.org/2000/svg

然后您必须使用 createElementNS()方法:

this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

关于css - 影子 dom 样式不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54918880/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com