2021年3月13日星期六

Applying selection style to slotted elements?

I'm trying to apply ::selection style on slotted elements within a web component.

Here is a small code to illustrates the issue:

window.customElements.define('x-widget', class extends HTMLElement {      constructor() {      super();          this.attachShadow({mode: 'open'});            const template = document.createElement('template');      template.innerHTML = `          <div>TEMPLATE</div>        <div><slot></slot></div>      `;        const style = document.createElement('style');      style.textContent = `          :host {          display: inline;          contain: content;          color: red;        }            :host::selection, ::selection {          background: red;          color: white;        }          ::slotted(::selection) {          background: red;          color: white;        }      `;            this.shadowRoot.appendChild(style);          this.shadowRoot.appendChild(template.content.cloneNode(true));    }  });  
<x-widget>CONTENT1</x-widget>  <x-widget><div>CONTENT2</div></x-widget>  

Here is a demo: https://jsfiddle.net/h3o7mf0e/

The selection style is applied to all texts excepts <div>CONTENT2</div>. Is there a way to use pseudo-element selectors within the component?

https://stackoverflow.com/questions/66620986/applying-selection-style-to-slotted-elements March 14, 2021 at 12:05PM

没有评论:

发表评论