css 如何在shadow dom中添加样式表?

gg0vcinb  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(122)

我正在使用Web组件。我有下面的html结构

<div class="test"> 
   #shadow-root (open)
    <overlay-trigger type="modal">
        <div id = "login-dialog">
         #shadow-root (open)
         <div id = "modal">

字符串
我有以下代码

const styleString = String(styles);
const style = document.createElement("style");
style.type = "text/css";
style.innerHTML = styleString;

const styleString2 = String(guestModalStyles);
const style2 = document.createElement("style");
style2.type = "text/css";
style2.innerHTML = styleString2;

let host = this.renderRoot?.querySelector('overlay-trigger[type="modal"]')?.querySelector("#login-dialog")?.shadowRoot?.querySelector(".modal");
if (host) {
   host?.appendChild(style);
   host?.appendChild(style2);
}


如何向模式元素添加样式?class =“modal”的那个?我在上面做吗?

rm5edbpk

rm5edbpk1#

一个更简单的方法就是添加一个css路径getter函数(如下所示:Get CSS path from Dom element)添加到您的代码中(使用console.log或alert),然后删除代码,但保存选择器。
有了Element对象后,对其进行样式化就像

var elem = ...;
elem.style.color = "red";

字符串

db2dz4w8

db2dz4w82#

您的代码看起来大部分都是正确的,但是有几个更改可以确保样式应用于Shadow DOM中的正确组件。
与其使用这个.renderRoot,不如直接使用shadowRoot属性。如果您正在使用this.attachShadow()技术来创建Shadow DOM,则this.shadowRoot将为您提供Shadow DOM的基础。在Shadow DOM中使用querySelector时,您希望使用::shadow或::opened伪组件来选择Shadow DOM中的组件。
更改代码:

const styleString = String(styles);
const style = document.createElement("style");
style.type = "text/css";
style.innerHTML = styleString;

const styleString2 = String(guestModalStyles);
const style2 = document.createElement("style");
style2.type = "text/css";
style2.innerHTML = styleString2;

const overlayTrigger = this.shadowRoot.querySelector('overlay-trigger[type="modal"]');

if (overlayTrigger) {
  const loginDialog = overlayTrigger.shadowRoot.querySelector("#login-dialog");

  if (loginDialog) {
    const modal = loginDialog.shadowRoot.querySelector(".modal");

    if (modal) {
      modal.appendChild(style);
      modal.appendChild(style2);
    }
  }
}

字符串

bwleehnv

bwleehnv3#

你可以使用document.styleSheets属性来访问你的CSS页面(它返回一个数组,遍历数组来访问特定的CSS样式表),这些页面链接到你的html页面,并使用csspagefromstyleSheet。insertRule()方法来添加样式到你的CSS。

相关问题