利用随机数改变盒子样色,相邻两个不同色
这是一个随机数应用的小例子,简单明了:
<body>
<style>
#wrapper{width:300px;margin:0 auto;}
#wrapper li{height:50px;text-align: center;font-size:18px;line-height: 50px;list-style-type:none;}
</style>
<div id="wrapper">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<script>
window.onload = function(){
for (var i = 0; i < document.querySelectorAll("#wrapper ul li").length; i++) {//querySelector 和 querySelectorAll 方法是 W3C Selectors API 规范中定义的。他们的作用是根据 CSS 选择器规范,便捷定位文档中指定元素。
document.querySelectorAll("#wrapper ul li")[i].colorfulBg();
}
}
// JavaScript Document
var colors=["#69D2E7","#A7DBD8","#E0E4CC","#F38630","#FA6900","#C02942","#53777A"];
var rd = parseInt(Math.random()*colors.length);
this.style.backgroundColor=colors[rd];
if(this.previousElementSibling){
changeColor(this)
}
//这个只是让他好看一点而已,并没有什么卵用
Element.prototype.colorfulBg=function(){
function changeColor(e){
if (e.style.backgroundColor!=e.previousElementSibling.style.backgroundColor){
return; //判断此盒子与上一个盒子颜色是否相同
}else{
var rd = parseInt(Math.random()*colors.length);//random();0-1随机数
e.style.backgroundColor=colors[rd];
return changeColor(e);
}
}
}
</script>
</body>

浙公网安备 33010602011771号