我尝试将 img 放入 div 的特定位置 (200, 100),但它始终位于左上角 (0, 0)。我做错了什么?
<!doctype html>
<html>
<head>
<title>Matching Game</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body id="theBody" onload="build_set()">
<h1>Matching Game</h1>
<div id="leftSide" style="position:absolute; top:100px; left:0; width:500px; height:500px"></div>
<div id="rightside" style="position:absolute; top:100px; left:500px; width:500px; height:500px; border-left:3px solid black"></div>
<script>
function build_set() {
var leftSide = document.getElementById("leftSide");
var rightSide = document.getElementById("rightSide");
var smile = document.createElement("img");
smile.setAttribute("src", "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png")
smile.style.top = "200px";
smile.style.left = "100px";
leftSide.appendChild(smile);
}
</script>
</body>
</html>
最佳答案
您还需要为 img 设置 position
。这是 jsFiddle
function build_set() {
var leftSide = document.getElementById("leftSide");
var rightSide = document.getElementById("rightSide");
var smile = document.createElement("img");
smile.setAttribute("src", "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png")
smile.style.top = "200px";
smile.style.left = "100px";
smile.style.position = "absolute";
leftSide.appendChild(smile);
}
build_set();
<h1>Matching Game</h1>
<div id="leftSide" style="position:absolute; top:100px; left:0; width:500px; height:500px"></div>
<div id="rightside" style="position:absolute; top:100px; left:500px; width:500px; height:500px; border-left:3px solid black"></div>
关于javascript - 图像元素未正确放置在 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34921740/