質問するログイン新規登録

回答編集履歴

1

修正

2017/01/14 08:36

投稿

s8_chu
s8_chu

スコア14731

answer CHANGED
@@ -26,21 +26,21 @@
26
26
  <div id="content"></div>
27
27
  <button id="btn">クリック</button>
28
28
  <script>
29
- function setRandomLeft() {
29
+ function setRandomLeft(imageWidth) {
30
- return (Math.random() * (document.getElementById("content").clientWidth - 100)) + "px";
30
+ return (Math.random() * (document.getElementById("content").clientWidth - imageWidth)) + "px";
31
31
  }
32
32
 
33
- function setRandomTop() {
33
+ function setRandomTop(imageHeight) {
34
- return (Math.random() * (document.getElementById("content").clientHeight - 100)) + "px";
34
+ return (Math.random() * (document.getElementById("content").clientHeight - imageHeight)) + "px";
35
35
  }
36
36
 
37
37
  document.getElementById("btn").addEventListener("click", function () {
38
- document.getElementById("content").innerHTML = "";//すでに画像があったらここで取り除く。
38
+ document.getElementById("content").innerHTML = "";
39
39
  var image = document.createElement("img");
40
40
  image.src = "https://placehold.jp/100x100.png";
41
41
  image.style.position = "absolute";
42
- image.style.top = setRandomTop();
42
+ image.style.top = setRandomTop("100");//画像の横の長さをsetRandomTopに。
43
- image.style.left = setRandomLeft();
43
+ image.style.left = setRandomLeft("100");//画像の縦の長さをsetRandomLeftに。
44
44
  document.getElementById("content").appendChild(image);
45
45
  });
46
46
  </script>