在Shadow DOM中,覆盖CSS正文*

问题描述 投票:0回答:1

我有以下情况:

Printscreen of my problem

我在项目中有一个CSS(无法更改),定义以下内容:

body * {
  font-family: 'x'
}

Essess CSSestáinfluenciando no meu shadow DOM,por causa disso,eunãoconsigo都使用了专有权font-family sem utilizar !important。 Apenas com !important funciona。Alguémsabe o que fazer nesse caso?

并且此CSS正在影响我的影子DOM,因此,如果不使用!important,就无法使用font-family属性。仅在!重要起作用:

::slotted(span), ::slotted(p){
    font-family: arial !important;
}

有人知道在这种情况下该怎么办吗?

javascript css reactjs shadow-dom custom-element
1个回答
0
投票

[::slotted仅适用于放置在阴影DOM中的CSS内部-参见documentation-

您的情况,我猜您想要

greg-alert span, greg-alert p { 
    font-family: arial; 
}

或者也许将<style>添加到shadowroot-如下所示this example中所示>

customElements.define('person-details',
  class extends HTMLElement {
    constructor() {
      super();

      const template = document.getElementById('person-template');
      const templateContent = template.content;

      const shadowRoot = this.attachShadow({mode: 'open'});

      const style = document.createElement('style');
      style.textContent = `
        div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }
        h2 { margin: 0 0 10px; }
        ul { margin: 0; }
        p { margin: 10px 0; }
        ::slotted(*) { color:grey;  font-family: serif}
      `;

      shadowRoot.appendChild(style);
      shadowRoot.appendChild(templateContent.cloneNode(true));
  }
});
body {
  font-family: monospace;
}
person-details p {
  font-family: sans-serif;
}
<h1>::slotted pseudo-element example</h1>

<template id="person-template">
  <div>
    <h2>Personal ID Card</h2>
    <slot name="person-name">NAME MISSING</slot>
    <ul>
      <li><slot name="person-age">AGE MISSING</slot></li>
      <li><slot name="person-occupation">OCCUPATION MISSING</slot></li>
    </ul>
  </div>
</template>

    <person-details>
      <p slot="person-name">Morgan Stanley</p>
      <span slot="person-age">36</span>
      <span slot="person-occupation">Accountant</span>
    </person-details>

    <person-details>
      <p slot="person-name">Dr. Shazaam</p>
      <span slot="person-age">Immortal</span>
      <span slot="person-occupation">Superhero</span>
    </person-details>

    <person-details>
      <p slot="person-name">Boris</p>
      <span slot="age">27</span>
      <span slot="i-am-awesome">Time traveller</span>
    </person-details>

如果检查元素,您会发现

  • 默认样式为monospace(由“外部” CSS设置)
  • 开槽的元素为serif(由shadowroot附加样式设置)
  • 但是p内的person-detailssans-serif(由“外部” CSS设置)
  • 全部不需要!important

© www.soinside.com 2019 - 2024. All rights reserved.