Use CSS selectors like :first-child inside shadow dom

后端 未结 2 1376
无人共我
无人共我 2021-01-26 15:20

Is there any way to use css selectors like :first-child, :not(:last-child) inside of the shadow dom?

The example is like this

CustomElement.html

         


        
2条回答
  •  醉话见心
    2021-01-26 15:35

    I found a workaround for this in JS way.

    For each slot, we have a eventHandler called (slotchange). By using that we can get the DOM event for the slot whenever the slot changes. Like this (HTML)

    
    

    JS

    onSlotChanged($event) {
     console.log($event) // Go and research yourself about this event, you'll find many things usefull.
     $event.target.assignedNodes() // This will give you the array of every elements, that are in side of the shadow dom
     // Example usage, adding the margin-bottom to only first time (css :firsh-child)
     $event.target.assignedNodes()[0].shadowRoot.getElementById('some-id').style.marginBottom = '10px'
    }
    

    If you only need to add a property to the element, you don't have to query shadowDom like "node.shadowRoot". But, if you want to access the element inside the shadowRoot of that element, you have to use that

提交回复
热议问题