我想在单击按钮后生成一个新的 div 并将其插入到页面上的其他元素之上。我正在编写以下标记:
<div id="parent">
<div id="d1">
</div>
<div id="d2">
</div>
<div id="d3">
</div>
<input type="button" id="but"/>
</div>
样式:
#d1{
width:200px;
height:200px;
background-color: black;
}
#d2{
width:200px;
height:200px;
background-color: aqua;
}
#d3{
width:200px;
height:200px;
background-color: blue;
}
和脚本:
var but=document.getElementById("but");
var d3=document.getElementById("d3");
var p=document.createElement("div");
p.setAttribute("style", "position:absolute; top:400, background-color: grey;width:10px; height:10px;");
var parent= document.getElementById("parent");
but.onclick=function(){
parent.insertBefore(p,d3);
}
但在我单击一个按钮后,div 插入到另一个 div 下。这是 jsFiddle例子。如何解决?
最佳答案
在您的代码中,您在 top:400 之后使用了逗号而不是分号:
position:absolute; top:400, background-color: grey;
正确的代码是:
position:absolute; top:400; background-color: grey;
关于javascript - 将由脚本插入和生成的 div 定位到其他元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971215/