我试图在div中并排排列4个元素。其中两个是图像,其中两个是段落标记。
像这样:[img1] - [p1] - [img2] - [p2]
以下是我的代码。但是,元素垂直显示在彼此之上。我希望他们在同一条线上。我怎么能这样做?
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var t1 = document.createTextNode("A");
var t2 = document.createTextNode("B");
p1.appendChild(t1);
p2.appendChild(t2);
var parent_div = document.createElement("div");
parent_div.classList.add("my_div");
$(".my_div").css('display','inline-block');
//$(".my_div").css('float','left');
var img1 = document.createElement("img");
var img2 = document.createElement("img");
img1.src = "image1.png";
img2.src = "image2.png";
parent_div.appendChild(img1);
parent_div.appendChild(p1);
parent_div.appendChild(img2);
parent_div.appendChild(p2);
答案 0 :(得分:1)
您需要为孩子设置样式,而不是让<input type=radio name=my_radio value=value_1>
var my_form = document.querySelector('#my_form');
var my_radio = my_form.elements.my_radio;
alert(my_radio.value) // this is the radionodelist.value you can check it on mdn
元素为.my_div
display
。这可以通过履行inline-block
来完成。另请注意,必须在 元素添加到页面后应用
或者,这可以在CSS中完成:
$(".my_div img, .my_div p").css('display', 'inline-block')
可以在以下示例中看到:
.my_div > img, .my_div > p {
display: inline-block;
}
&#13;
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var t1 = document.createTextNode("A");
var t2 = document.createTextNode("B");
//p1.appendChild(pos_percent);
//p2.appendChild(neg_percent);
p1.innerHTML = 'a';
p2.innerHTML = 'b';
var parent_div = document.createElement("div");
parent_div.classList.add("my_div");
var img1 = document.createElement("img");
var img2 = document.createElement("img");
img1.src = "http://placehold.it/100";
img2.src = "http://placehold.it/100";
parent_div.appendChild(img1);
parent_div.appendChild(p1);
parent_div.appendChild(img2);
parent_div.appendChild(p2);
// Sample
var example = document.getElementById('example');
example.appendChild(parent_div);
$(".my_div img, .my_div p").css('display', 'inline-block');
&#13;
答案 1 :(得分:0)
您的孩子没有显示内联的原因是因为您只在父div而不是其子女上设置它。
尝试将此添加到您的CSS:
.parent_div{
display: flex;
flex-direction: row;
justify-content: centre/space-around/space-between;
}
或者,您可以将每个孩子设置为display: inline block
像这样:
parent_div.appendChild(img1).classList.add("my_div");