我試圖讓smile.png圖像出現在特定<div>
內的隨機位置的圖像的位置。我怎麼能隨意在JavaScript設置
我所做的是設置variable.style.top= top_position+'px'
& variable.style.left = left_position+"px"
。
然而,我所得到到目前爲止是水平排列,而不是隨機定位的圖像。我怎麼能做到這一點?
var theLeftSide = document.getElementById("leftSide");
var randomY = Math.round(Math.random()) + 'px';
var randomX = Math.round(Math.random()) + 'px';
function generateFaces() {
for (numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
createElement(numberOfFaces);
}
}
number = 0;
function createElement() {
number++;
//creating the image on the leftside
var smiley = document.createElement('img');
smiley.src = "smile.png";
smiley.style.position = "absolute";
smiley.style.left = randomX;
smiley.style.top = randomY;
theLeftSide.appendChild(smiley);
}
#leftSide {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
position: absolute;
width: 500px;
height: 500px;
left: 500px;
border-left: 1px solid black;
}
<body id="smileyGuessingGame" 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>
有在你的代碼中的一些語法錯誤。試試這個:https://jsfiddle.net/ptv2c6jd/ – Rayon
@RayonDabre編輯 – Luke
試試這個:https://jsfiddle.net/ptv2c6jd/1/'toFixed'會返回字符串,''parseInt'應該用.. – Rayon