首页 > 解决方案 > 阴影 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;
  `;
}

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

标签: cssweb-componentshadow-dom

解决方案


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

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

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

推荐阅读