使用javascript生成div内的随机位置
我正在寻找一种方法来生成我的html div上的随机位置。我创建了一个JavaScript函数,它看起来像这样:使用javascript生成div内的随机位置
function randomInRange(min, max) {
return(Math.floor((Math.random() * (max - min) + 1) + min));
}
我想通过改变来产生div的CSS的随机位置(位置:亲属;左:0像素;顶:0像素)的左侧和顶部属性到随机生成的数字。我似乎无法找到该函数的最小值,因为div使用宽度的百分比。
CSS的div:
#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,最大值为元素的宽度和高度属性。 See here for an understanding of the different width properties。
我假设你想要element.outerWidth(true)
和element.outerHeight(true)
。
var stage = document.getElementById('stage');
var stageWidth = stage.offsetWidth;
var stageHeight = stage.offsetHeight
现在你可以使用stageWidth & stageHeight为你的函数调用
使用clientWidth
和width
和height
button.onclick = function() {
shape.style.left = randominrange(0, stage.style.clientWidth);
shape.style.top = randominrange(0, stage.style.clientHeight);
}
这里clientHeight
反而是clientHeight vs offsetHeight
谢谢!它的工作,但随机的位置往往得到更远的div和溢出 –
调试,我需要看到你的标记。 – gurvinder372
所以问题之间的区别是你无法找到div的宽度? –