创建的图像元素未放置在 div 内的正确位置
Created image element is not placed at the correct location inside a div
我有一个 HTML,其中有一些 div 个元素,例如:
<body id="theBody">
<div id="box1">
<div id="boxLeft"></div>
<div id="boxRight"></div>
</div>
...
在 JavaScript 代码中我做了这样的事情:
var theLeftSide = document.getElementById("boxLeft");
newImg = document.createElement("img");
newImg.src = "image1.png";
topPos = 200;
leftPos = 200;
newImg.style.top = topPos + "px";
newImg.style.left = leftPos + "px";
newImg.setAttribute("width", "60px");
theLeftSide.appendChild(newImg);
我希望图像显示在 boxLeft
内的正确位置 (200, 200),但它显示在页面的左上角。
我做错了什么?
感谢任何帮助。
您需要对图像应用绝对定位。
#boxLeft img {
position: absolute;
}
或newImg.style.position= "absolute";
尝试添加这个 css:
#boxLeft{
position: relative;
}
img{
position: absolute;
}
我有一个 HTML,其中有一些 div 个元素,例如:
<body id="theBody">
<div id="box1">
<div id="boxLeft"></div>
<div id="boxRight"></div>
</div>
...
在 JavaScript 代码中我做了这样的事情:
var theLeftSide = document.getElementById("boxLeft");
newImg = document.createElement("img");
newImg.src = "image1.png";
topPos = 200;
leftPos = 200;
newImg.style.top = topPos + "px";
newImg.style.left = leftPos + "px";
newImg.setAttribute("width", "60px");
theLeftSide.appendChild(newImg);
我希望图像显示在 boxLeft
内的正确位置 (200, 200),但它显示在页面的左上角。
我做错了什么?
感谢任何帮助。
您需要对图像应用绝对定位。
#boxLeft img {
position: absolute;
}
或newImg.style.position= "absolute";
尝试添加这个 css:
#boxLeft{
position: relative;
}
img{
position: absolute;
}