简体   繁体   中英

Math.random not working

I'm not able to generate value to place X in an random location within a box. Any idea what is wrong?

   var putAnXBtn = document.getElementById("putAnXButton");
putAnXBtn.onclick = function(){

        var theBox = document.getElementById("putAnX");

        // width and height of the box 
        var width = theBox.clientWidth;
        var height = theBox.clientHeight;


        var yPosition = Math.random()* width; // Not able to generate a value between 0 and the height
        var xPosition = Math.random()* height;  //Not able to generate a value between 0 and the width


      var theXElement = document.getElementById("theX");
        theXElement.innerHTML="X";
        theXElement.style.top = parseInt(yPosition)+'px';
        theXElement.style.left = parseInt(xPosition)+'px';

 }

I suggest to use

Math.floor(Math.Random() * width)
Math.floor(Math.Random() * height)

plus you have your height and width inverted while generating the random position.

Change this:

var yPosition = Math.random() * width;
var xPosition = Math.random() * height;

to this:

var yPosition = Math.floor(Math.random() * height);
var xPosition = Math.floor(Math.random() * width);

otherwise the X could be created outside of the container boundaries.

FIDDLE http://jsfiddle.net/9t46F/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM