Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript在div中生成随机位置_Javascript_Html_Css_Random - Fatal编程技术网

使用javascript在div中生成随机位置

使用javascript在div中生成随机位置,javascript,html,css,random,Javascript,Html,Css,Random,我正在寻找一种在html分区上生成随机位置的方法。我创建了一个javascript函数,如下所示: function randomInRange(min, max) { return(Math.floor((Math.random() * (max - min) + 1) + min)); } 我想通过将left和top属性更改为随机生成的数字(position:relative;left:0px;top:0px),在div的css中生成一个随机位置。我似乎找不到函数的ma

我正在寻找一种在html分区上生成随机位置的方法。我创建了一个javascript函数,如下所示:

function randomInRange(min, max) {
    return(Math.floor((Math.random() * (max - min) + 1) + min));    
}  
我想通过将left和top属性更改为随机生成的数字(position:relative;left:0px;top:0px),在div的css中生成一个随机位置。我似乎找不到函数的max&min值,因为div使用了宽度的百分比

分区的css:

#stage {
    float: left;
    background-color: pink;
    width: 100%;
    height: 70%;
}
当我单击某个按钮时,该函数将执行

var button = document.getElementById("button");

button.onclick = function () {
    shape.style.left = randominrange(0, stage.style.width);
    shape.style.top = randominrange(0, stage.style.height);   
}
//the shape is a circle div that shows where the generated point is

我几天前刚开始使用javascript,似乎找不到一种方法来实现它

最小值为0,最大值为元素的适当宽度和高度属性


我假设您想要
元素。outerWidth(true)
元素。outerHeight(true)
最小值为0,最大值为元素的适当宽度和高度属性

我假设您想要
element.outerWidth(true)
element.outerHeight(true)

现在,您可以对函数调用使用stageWidth和stageHeight


现在,您可以对函数调用使用stageWidth和stageHeight

使用
clientWidth
clientHeight
而不是
width
height

button.onclick = function () {
    shape.style.left = randominrange(0, stage.style.clientWidth);
    shape.style.top = randominrange(0, stage.style.clientHeight);   
}

这里是使用
clientWidth
clientHeight
而不是
width
height
之间的区别

button.onclick = function () {
    shape.style.left = randominrange(0, stage.style.clientWidth);
    shape.style.top = randominrange(0, stage.style.clientHeight);   
}

这里是

之间的差异,所以问题是找不到div的宽度?所以问题是找不到div的宽度?谢谢!它起作用了,但随机位置通常会超出div并溢出,谢谢!它起作用了,但随机位置通常会超出div并溢出