css - 阴影 dom 样式未显示
问题描述
通过此实例化的 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);
}
但是,样式属性在 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;
`;
}
我不确定为什么这两个行为不同。
解决方案
如果使用 定义 SVG 元素createElement
,则应设置特定的 SVG 命名空间http://www.w3.org/2000/svg
.
然后你必须使用createElementNS()
方法:
this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
推荐阅读
- git - 是否可以创建仅推送少数本地累积提交的 shell 脚本?
- c++ - C ++如何编写一个采用两个矩阵并计算行数和列数的方法
- java - 检查一个列表的间隔是否与另一个列表的间隔重叠
- prometheus - 尝试将 arangoDB 外部服务监视器添加到 Prometheus 服务监视器时应用来自 Terraform 的错误
- docker - nginx如何确定content-type头?
- r - R magick 功能相当于 IM6 convert -unsharp
- regex - 用 mod_rewrite 匹配多个相同参数的实例
- c - 害怕覆盖结构中的引用数据
- django - 上传到服务器 django rest api 的问题
- amazon-dynamodb - 在 dynamodb 上设计数据模型 - 选择正确的分区键