:host 选择器不适用于具有阴影的自定义元素 dom

:host selector not working for custom element having shadow dom

我正在尝试创建一个带有阴影 dom 的自定义组件。自定义组件已创建并添加到 dom 并附有阴影 dom,但未应用 :host 样式

HTML

<html>
  <head></head>
  <body>
    <notify-user>
      <h3 slot='title'>New message in #customer-support</h3>
      <p>This is shadow dom in action</p>
      <button>Reply</button>
    </notify-user>
    <script src='main.js' type="text/javascript"></script>
  </body>
</html>

JS

class Notification extends HTMLElement{
    constructor(){
        super();
    }
    connectedCallback(){
        console.log('notification custom element attached to DOM');
        console.log('this',this);
        let nRoot = this.attachShadow({mode : 'open'});
        nRoot.innerHTML = `
                    <style>
                        :host{
                            background-color : #3498db;
                            border-radius : 5px;
                            line-height: 1.4;
                            width: 25rem;
                        }
                        button {
                            min-width : 5rem;
                            padding: 0.5rem 2rem;
                            margin: 0.2rem;
                            background-color: transparent;
                            border-radius: 2px;
                            border: none;
                            color : white;
                        }
                        p{
                            color : white;
                        }
                    </style>    
                    <div class="wrapper">
                        <button><span>X<span></button>
                        <slot name='title'></slot>
                        <slot></slot>
                        <p>1 minute ago</p>
                    </div>`;

    }
}

customElements.define('notify-user',Notification);

当我 运行 这是为 :host 定义的浏览器样式未应用。

有人可以帮忙吗?

这里应用了:host选择器。问题是,您的宿主元素没有可显示的可见内容。

此问题的一个简单解决方法是将 CSS 显示设置设置为 'block',以使元素可见:

:host {
    background-color: #3498db;
    border-radius: 5px;
    line-height: 1.4;
    width: 25rem;
    display: block;
}