简体   繁体   English

Math.random不起作用

[英]Math.random not working

I'm not able to generate value to place X in an random location within a box. 我无法生成将X放在框内随机位置的值。 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. 另外,您在生成随机位置时会颠倒heightwidth

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. 否则,X可能会在容器边界之外创建。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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