首页 > 解决方案 > 如何使用 div 使用 javascript 设置单选按钮的样式

问题描述

我试图让单选按钮一个接一个地出现,每个按钮都有它们的标签。我使用了一个循环,它遍历 json 文件的内容并成功创建了带有标签的单选按钮,但它们彼此相邻出现: 在此处输入图像描述

我试图将单选按钮和标签包装在一个 div 中,以便它们显示在另一个之下,但我不知道该怎么做。这是我到目前为止所拥有的:


for (const o of i.options){

        const x = document.createElement("INPUT");
        x.setAttribute("type", "radio");
        x.setAttribute("id", "lord");
        window.data.appendChild(x);


        const y = document.createElement("LABEL");
        const t = document.createTextNode(o);
        y.textContent = "Label text";
        y.setAttribute("for", "lord");
        window.data.appendChild(t);

        const div = document.createElement("div");
        div.style.width = "200px";
        div.style.height = "5px";
        document.getElementById("radioButton1").appendChild(div);
      }

标签: javascriptradio-buttonlabel

解决方案


不是将radioand附加label到窗口,而是将它们附加到div然后附加div到父元素。

由于div是块级元素,它应该垂直出现

for (const o of i.options) {

  const x = document.createElement("INPUT");
  x.setAttribute("type", "radio");
  x.setAttribute(o.id, "lord"); // if there is id key available 


  const y = document.createElement("LABEL");
  const t = document.createTextNode(o);
  y.appendChild(t); // cheanged here
  y.setAttribute("for", "lord");


  const div = document.createElement("div");
  div.style.width = "200px";
  div.style.height = "5px";
  div.appendChild(x); //changed here
  div.appendChild(y); //changed here
  document.getElementById("radioButton1").appendChild(div);
}

推荐阅读