【问题标题】:Appending a button to an existing shadowroot element is not correct将按钮附加到现有的 shadowroot 元素是不正确的
【发布时间】:2021-02-03 07:27:44
【问题描述】:

var shadow = document.getElementById(
        "3rd-party-div"
      ).shadowRoot; 
      
let style = document.createElement("style");
      style.textContent = `
      .custom_button{
    
    padding: 10px;
    display:block;
    float:left;
    text-align:center;
}
`
shadow.appendChild(style);
let customButton = document.createElement("button");
customButton.setAttribute("class", "custom_button");
customButton.innerHTML = "Back to Overview";
      
      

我的 HTML 页面中有一个 shadowRoot,我通过这段代码访问它

var shadow = document.getElementById(
        "3rd-party-div"
      ).shadowRoot; 

现在我想创建一个按钮并将其附加到这个 shadowroot。下面的代码-

      let customButton = document.createElement("button");
      customButton.setAttribute("class", "custom_button");
      customButton.innerHTML = "Back to Overview";

然后我使用此代码shadow.appendChild(customButton);将此按钮附加到阴影元素 我有我的 css 样式,我也将其附加到 shadowroot。

现在我的按钮出现在页面中,但它位于我的 shadowroot div 下方。有没有办法把它作为我的影子 div 本身的一部分?

【问题讨论】:

  • shadow.appendChild 会将其附加到影子根。是否要将其附加到影子主机(“3rd-party-div”元素),使其成为影子根的兄弟?
  • 单击编辑器中的 [] 图标并尝试在您的问题中包含一个有效的代码段。你现在提到了很多我们看不到代码的成分。
  • @Danny'365CSI'Engelman 添加了 sn-p。
  • @MiKo 现在说得通了。我的 3rd-party-div 元素里面有另一个 div,我想做的是将它附加到那个 div。在我的代码中,我将它直接附加到 shadow root,这就是它没有正确出现的原因。有没有办法将我的按钮附加到我的 shadowroot 内的 div 中?
  • @user1734698 我发布了一个答案,这是你想要的吗?

标签: javascript html shadow-dom


【解决方案1】:

我不确定我是否完全理解您想要实现的目标,但根据您最近的评论,我认为您希望保留 div 的内容,将影子 DOM 附加到它并在同一个 div 中添加一个按钮。

附加阴影will replace the original DOM subtree of the host。如果你想保留它,你可以使用<slot>

const thirdPartyDiv = document.getElementById("3rd-party-div");

// Button inside the 3rd-party-div
const customButtonExt = document.createElement("button");
customButtonExt.innerHTML = "Back to Overview (inside 3rd party div)";
thirdPartyDiv.appendChild(customButtonExt);

// Attach shadow and keep the content of the div by using a <slot>
thirdPartyDiv.attachShadow({ mode: "open" }).innerHTML = '<slot></slot>';
      
const shadow = thirdPartyDiv.shadowRoot; 
      
const style = document.createElement("style");
style.textContent = `
  .custom_button {
    padding: 10px;
    display:block;
    float:left;
    text-align:center;
}
`;
shadow.appendChild(style);

// Button inside the shadow
const customButton = document.createElement("button");
customButton.setAttribute("class", "custom_button");
customButton.innerHTML = "Back to Overview (inside shadow)";

shadow.appendChild(customButton);
<div id="3rd-party-div">
  <div>Content of the 3rd-party div!</div>
</div>

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 2019-10-17
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    相关资源
    最近更新 更多