:主机选择器不适用于具有shadow dom的自定义元素

Nis*_*ava 2 html javascript css web-component

我正在尝试创建一个附加有 Shadow dom 的自定义组件。自定义组件被创建并添加到带有 Shadow dom 的 dom 中,但 :host 样式不会被应用

超文本标记语言

<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>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

当我运行时,这是为 :host 定义的浏览器样式不会被应用。

有人可以帮忙吗?

jen*_*ter 6

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

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

:host {
    background-color: #3498db;
    border-radius: 5px;
    line-height: 1.4;
    width: 25rem;
    display: block;
}
Run Code Online (Sandbox Code Playgroud)