在JavaScript(DOM)中显示图像的问题

时间:2016-01-12 19:15:09

标签: javascript html dom

我的任务是将5个图像(smile.png)添加到页面左半部分的5个随机位置,这是一个div = id =" leftSide"和尺寸500x500px 所以这是我的代码



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;
  }
}
&#13;
img {
  position:absolute
}
div {
  position:absolute;
  width:500px;
  height:500px;
}
#rightSide { 
  left: 500px; 
  border-left: 1px solid black; 
}
&#13;
<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>
&#13;
&#13;
&#13;

应该这样做 this 但相反,它只显示一个白页。

1 个答案:

答案 0 :(得分:0)

将createElement更改为新的Image();

var this_img=new Image();