阴影 DOM:附加到阴影 DOM 的元素未渲染

Shadow DOM: Elements attached to shadow DOM not rendering

我正在尝试了解单选按钮在阴影中的工作方式 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>

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

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>