Shadow DOM styling from the outside

后端 未结 3 1523
难免孤独
难免孤独 2020-12-20 12:12

I am searching a way to styling shadow DOM from the outside. For example, I would like to set the color of all text in all \'span.special\' elements as RED. Including \'span

3条回答
  •  醉梦人生
    2020-12-20 12:28

    I did try many methods, including those described here. Since I'm using an external Web Component lib, I don't have access to modify these components. So, the only solution that worked for me was using JS querySelector, like this:

    document.querySelector("the-element.with-shadow-dom")
      .shadowRoot.querySelector(".some-selector").setAttribute("style", "color: black");
    

    Not the best solution, not suitable for large stylings, but does work for little enchancements.

    @John this was tested with Chrome 83.0.4103.116 (still going to test in Safari) and I did for Ionic (v5) ion-toast component. Here is the (almost) real code I used:

      import { toastController } from '@ionic/core';
    
      let toastOpts = {
        message: "Some message goes here.",
        cssClass: "toast-with-vertical-buttons",
        buttons: [
          {
            text: "Button 1",
            side: 'end'
          },
          {  
            text: "Button2",
            side: 'end'
          },
          {
            icon: "close",
            side: "start"
          }
        ]
      }
      toastController.create(toastOpts).then(async p => {
        let toast = await p.present(); // this renders ion-toast component and returns HTMLIonToastElement
        toast.shadowRoot.querySelector('div.toast-button-group-end').setAttribute("style", "flex-direction: column");
      });
    

提交回复
热议问题