
如何实现随机显示DIV
假设有6个DIV,想要随机显示其中2个,请教大神们,这要如何实现?代码请尽量完整,最好复制就能运行,这样我就可以及时给分,谢谢大神。...
假设有6个DIV,想要随机显示其中2个,请教大神们,这要如何实现?代码请尽量完整,最好复制就能运行,这样我就可以及时给分,谢谢大神。
展开
2个回答
展开全部
哎呀,你知道js的那个啦
Math.floor(Math.random()*6)
这个就是随机的从0-5里面选择,这么简单,你还有疑问么?!
如果还有的话,你就看div嘛
你可以设置div的id嘛,是吧!id从0到6编号嘛,对吧,
例如div0-div5,是吧
然后呢,你还可以测试一下嘛,对吧
测试代码如下嘛. 你可以换成你的显示可见嘛 那个啊
<!DOCTYPE html>
<html>
<meta charset=utf-8 />
<title>Sliding Puzzle (2x2)</title>
<head>
<script>
function testRandomColor () {
var rand1 = Math.floor(Math.random()*6);
var rand2 = Math.floor(Math.random()*6);
while (rand1 == rand2) {
rand2 = Math.floor(Math.random()*6);
}
for (var i = 0; i < 6; i++) {
document.getElementById('div'+i).style.backgroundColor='';
}
document.getElementById('div'+rand1).style.backgroundColor='red';
document.getElementById('div'+rand2).style.backgroundColor='blue';
}
</script>
</head>
<body>
<input type="button" value="test" onclick="testRandomColor();" />
<div id="div0">div0</div>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<div id="div5">div5</div>
</body>
</html>
如果还不清楚的话,anytime anyplace call我啊,奉陪到底啊,
展开全部
生成2次随机数Math.random(6)-1,if判断如果第2次与第1次重复则重复生成
用jQuery的hide方法来隐藏所有div。
用jQuery('div').eq(第1个随机数) 和 jQuery('div').eq(第2个随机数), 的show()方法,来展示结果
用jQuery的hide方法来隐藏所有div。
用jQuery('div').eq(第1个随机数) 和 jQuery('div').eq(第2个随机数), 的show()方法,来展示结果
追问
能否给份完整的代码呢?对这一块确实不大懂呢,谢谢啊!
追答
$(function(){
$('div').hide();
function randNum(){ var xx = Math.ceil(Math.random()*6)-1; return xx}
var r1=randNum(),r2=randNum();
while(r2==r1){ r2=randNum()}
$('div').eq(r1).show();
$('div').eq(r2).show();
})
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询