我试图在for循环中生成5个不同的随机数来生成5个图像,但是5个随机数生成的完全相同! var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
for (var i = 0; i < numberOfFaces; i++) {
//create image
var img = document.createElement('img');
img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var random1 = Math.floor(Math.random() * 500 - (100 * i));
var random2 = Math.floor(Math.random() * 500 - 100 * i);
img.style.top = random1;
img.style.left = random2;
document.body.appendChild(img);
}
答案 0 :(得分:8)
并不是随机数不是随机数,而是设置css值你也需要一个单位,比如像素,百分比等。
render() {
var {children} = this.props
children[0].x // it doesn't work
...
要使这些CSS值生效,元素的位置必须不是img.style.top = random1 + 'px';
img.style.left = random2 + 'px';
static
答案 1 :(得分:1)
(先生检查你的随机数生成声明)
Mozilla Developer中心页面上有一些示例:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}