Web组件:主机:悬停

Webcomponents :host:hover

有没有办法在 web 组件上添加 css :hover 效果(不是来自父组件)。

我有以下示例代码

window.customElements.define('a-b', class extends HTMLElement {
  constructor() {
      super();
      this.attachShadow({mode: 'open'}).innerHTML = `
        <style>
          :host {
            display: block;
            height: 100px;
            width: 100px;
            background: red;
          }
          :host:hover {
            background: blue;
          }
          :host::selection {
            background: rgba(0, 0, 0, 0.15);
          }
        </style>
        <slot></slot>
      `;
  }
}

:host::selection 属性 按预期工作。但是:host:hover似乎没有任何效果。

我知道有解决此问题的方法,例如:

但我想知道我是否只是为了更清晰的代码而遗漏了一些东西(因为这看起来不太复杂)。

为了使代码更简洁,请改用 :host() 语法,因为 :hover 是应用于自定义元素的伪 class。然后可以选择:

:host(:hover) { ... }

示例:

window.customElements.define('a-b', class extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({mode: 'open'})
        .innerHTML = `
           <style>
              :host(:hover) {
                color: white;
                background-color: blue;
              }       
          </style>
          <slot></slot>`
  }
})
<a-b>Hello World</a-b>