I'm trying to create elements in random locations on the screen but I have run into some trouble. Creating the elements works but when I try to make them have random locations, nothing happens. Thanks for the help in advance.
Here's my code:
var newObject = document.createElement("DIV"); newObject.setAttribute("class", "object"); newObject.setAttribute("id", "powerup"); document.body.appendChild(newObject); var powerup = document.getElementById("powerup"); var object = document.getElementsByClassName("object"); for (i = 0; i < object.length; i++) { object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px"; object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px"; } function createObject() { var newObject = document.createElement("DIV"); newObject.setAttribute("class", "object"); newObject.setAttribute("id", "powerup"); document.body.appendChild(newObject); for (i = 0; i < object.length; i++) { object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px"; object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px"; } }
html, body { height: 100%; width: 100%; margin: 0; } #powerup { background: red; height: 10px; width: 10px; }
<body> <button onclick="createObject()">Create a Block</button> </body>
Your code is working correctly. Its able to set top and left of each #powerup
element. The only problem is that the position
of #powerup
is static
by default. So you just need to change css of #powerup
element to
#powerup {
background: red;
height: 10px;
width: 10px;
position: relative;
}
position: absolute
can also be used. Choose the one that fits your requirements.
I made a CodePen with your code.
For those elements to have their top
and left
properties have an effect, you need to add position: absolute;
to the #powerup
elements.
#powerup {
background: red;
height: 10px;
width: 10px;
position: absolute;
}
Also, I'm not sure if this is what you intended, but your JavaScript code is selecting a new random location for each pre-existing #powerup
element whenever you click the button.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.