【问题标题】:Shadow DOM: Elements attached to shadow DOM not renderingShadow DOM:附加到 shadow DOM 的元素未呈现
【发布时间】:2020-05-09 03:49:15
【问题描述】:

我试图了解单选按钮如何在影子 dom 中工作。我有一个脚本标签,我将一个影子 DOM 附加到一个元素,然后附加一些单选按钮。我的问题是单选按钮没有呈现。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>Radio Buttons:</p>
<div id="containter">

</div>

<script>
    let shadowContainer = document.getElementById('containter');
    shadowContainer.attachShadow({mode: 'open'});

    let input1 = document.createElement('input');
    input1.setAttribute("type", "radio");
    input1.setAttribute("id", "1");
    input1.setAttribute("name", "group");
    input1.setAttribute("value", "1");

    let input2 = document.createElement('input');
    input2.setAttribute("type", "radio");
    input2.setAttribute("id", "2");
    input2.setAttribute("name", "group");
    input2.setAttribute("value", "2");

    let input3 = document.createElement('input');
    input3.setAttribute("type", "radio");
    input3.setAttribute("id", "3");
    input3.setAttribute("name", "group");
    input3.setAttribute("value", "3");

    shadowContainer.appendChild(input1);
    shadowContainer.appendChild(input2);
    shadowContainer.appendChild(input3);
</script>
</body>
</html>

【问题讨论】:

  • 我不熟悉这种方法,但是developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow 的示例表明attachShadow() 方法返回一个元素,它是您附加元素的那个元素。
  • 好收获。 let container = document.getElementById('containter'); let shadowContainer = container.attachShadow({mode: 'open'}); 是我需要的。
  • 如果你把它放在答案中,那就是你的全部了。
  • 不,那只是我指着文档,:)
  • 真正的绅士。

标签: javascript html radio-button shadow-dom stenciljs


【解决方案1】:

问题是您没有将元素添加到 shadowDom,而是将它们添加到 div。只需存储来自.attachShadow 的返回值并附加到该值。这是您的示例。

let shadowContainer = document.getElementById('containter');
// store the reference
let container = shadowContainer.attachShadow({
  mode: 'open'
});

let input1 = document.createElement('input');
input1.setAttribute("type", "radio");
input1.setAttribute("id", "1");
input1.setAttribute("name", "group");
input1.setAttribute("value", "1");

let input2 = document.createElement('input');
input2.setAttribute("type", "radio");
input2.setAttribute("id", "2");
input2.setAttribute("name", "group");
input2.setAttribute("value", "2");

let input3 = document.createElement('input');
input3.setAttribute("type", "radio");
input3.setAttribute("id", "3");
input3.setAttribute("name", "group");
input3.setAttribute("value", "3");

// append to the reference 
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(input3);
<p>Radio Buttons:</p>
<div id="containter">

</div>

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 2020-03-16
    • 2013-07-06
    • 2014-11-24
    • 2021-01-04
    • 2015-05-08
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多