vendredi 4 novembre 2016

JavaScript - Math.floor(Math.random()) - Reposition element

I am trying to develop a function that randomly repositions an element on a web document. My current JavaScript program does not randomly change the element.style.left and element.style.top values of the element id = "image". Thanks for your help!

<html> <body>

<img id="image" src="happy.jpg" style="position:absolute;left:0px; 
top:0px; width:50px; height:50px;" />

<button onclick="RandomPositions()"> Random Position </button>

<script>
 function RandomPositions() {
    var Hero = document.getElementById("image");
    var x = Math.floor(Math.random() * 300);
    var HeroX = Hero.style.left;
    HeroX = x + 'px';
    var y = Math.floor(Math.random() * 300);
    var HeroY = Hero.style.top; 
    HeroY = y + 'px';
 }
</script>
</body>
</html>




Aucun commentaire:

Enregistrer un commentaire