【发布时间】:2016-01-13 03:55:23
【问题描述】:
我的任务是将 5 张图片 (smile.png) 添加到页面左半部分的 5 个随机位置,这是一个 id="leftSide" 且大小为 500x500px 的 div 所以这是我的代码
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var count = 0;
function generateFaces(){
while(count < numberOfFaces) {
var this_img=createElement("img");
this_img.src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var toppos = Math.random() * 400;
var top_pos = Math.floor(toppos);
var leftpos = Math.random() * 400;
var left_pos = Math.floor(leftpos);
this_img.style.left=left_pos + "px";
this_img.style.top=top_pos + "px";
theLeftSide.appendChild(this_img);
count+=1;
}
}
img {
position:absolute
}
div {
position:absolute;
width:500px;
height:500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
<body onload="generateFaces()">
<h1>Matching game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
应该可以 this 但它只显示一个白页。
【问题讨论】:
-
打开你的小提琴,按F12打开控制台,看看你自己有什么问题。
-
提示:jsFiddle 将代码包装在 onLoad 处理程序中,您必须设置“nowrap in body”选项。
createElement不存在 -
@adeneo 这就是该选项的作用,很高兴知道,谢谢。
标签: javascript html dom