Javascript 设置形状的随机大小、颜色和位置
我让这个div元素在鼠标点击时移动到一个随机的位置,但是它不考虑整个屏幕的宽度和高度,它消失了,使得它非常不适合被点击。我希望它考虑到屏幕的高度和宽度,所以它不会超出页面。我还希望div得到一个随机大小,每次单击它时,从一个固定的更大的大小开始,并让它始终转到一个更低的大小。最后,它可以在每次点击时获得随机颜色 Html: jQuery:Javascript 设置形状的随机大小、颜色和位置,javascript,jquery,Javascript,Jquery,我让这个div元素在鼠标点击时移动到一个随机的位置,但是它不考虑整个屏幕的宽度和高度,它消失了,使得它非常不适合被点击。我希望它考虑到屏幕的高度和宽度,所以它不会超出页面。我还希望div得到一个随机大小,每次单击它时,从一个固定的更大的大小开始,并让它始终转到一个更低的大小。最后,它可以在每次点击时获得随机颜色 Html: jQuery: $('#test').click(function() { var docHeight = $(document).height(),
$('#test').click(function() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax )
});
});
您应该选择
窗口
宽度和高度而不是文档
大小,文档大小可以大于窗口大小
要在每次单击时获得随机大小,您应该执行与“位置”基本相同的操作
width: Math.floor(Math.random() * divWidth),
height: Math.floor(Math.random() * divHeight)
每次它都会给你比以前更低的值
最后,要获得随机颜色,可以如下生成:
backgroundColor: "rgb(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + ")"
检查下面的代码片段
$(“#测试”)。单击(函数(){
var docHeight=$(document).height(),
docWidth=$(文档).width(),
$div=$(“#测试”),
divWidth=$div.width(),
divHeight=$div.height(),
heightMax=docHeight-divHeight,
widthMax=docWidth-divWidth;
$div.css({
左:Math.floor(Math.random()*widthMax),
顶部:Math.floor(Math.random()*heightMax),
宽度:数学地板(0.7,1)*等分宽度),
高度:数学楼层(0.7,1)*高度,
背景颜色:“rgb(“+Math.floor(Math.random()*256)+”、“+Math.floor(Math.random()*256)+”、“+Math.floor(Math.random()*256)+”)
});
});
函数GetRandomArbital(最小值、最大值){
返回Math.random()*(max-min)+min;
}
#测试{
位置:绝对位置;
宽度:100px;
高度:70像素;
背景色:#d2fcd9;
}
test div
谢谢,它真的完成了我的要求。一个小细节,我希望它按比例缩小。例如,我不希望它从1000像素变为1像素,而是1000像素,然后是835px,然后是521px,等等随机数,但这些随机数可以确保框仍然可以向上点击,直到你没有按过多次为止。
width: Math.floor(Math.random() * divWidth),
height: Math.floor(Math.random() * divHeight)
backgroundColor: "rgb(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + ")"