6个div块,随机颜色

4 篇文章 0 订阅

参加工作以后,基本用到的都是react,最近老大要求用h5+mui做出一款app,制作过程中发现很多原生js已经不熟悉,看来js基础忘得都差不多了,需要补习了。app中有一个要求是页面对应的几个模块每次打开都要显示不同的随机颜色。我就封装成了一个函数,有不足的地方,还希望多多指点。代码如下。

    
<div class="giveYouColorSeeSee">1</div>
<div class="giveYouColorSeeSee">2</div>
<div class="giveYouColorSeeSee">3</div>
<div class="giveYouColorSeeSee">4</div>
<div class="giveYouColorSeeSee">5</div>
<div class="giveYouColorSeeSee">6</div>

.giveYouColorSeeSee {
	width: 100px;
	height: 100px;
	border: 1px solid blue;
	display: inline-block;
	margin-top: 10px;
	margin-right: 10px;
}				
<script>
var giveColor = document.getElementsByClassName('giveYouColorSeeSee');
var color = ['#578fff', '#8c9ffd', '#ff7ea2', '#ffbf43', '#74dde3', 'red'];
function randomColorOn(giveColor,color){//参数1为获取的元素组,参数二为获取的颜色组
	var arr2 = [];
	for(var i = color.length; i > 0; i--) {
		const num = Math.floor(Math.random() * color.length); //获取随机数
		arr2.push(color[num]); //把随机数添加到数组中
		color.splice(num, 1); //删除原有数组的颜色
	}
				 
	for(var j = 0; j < giveColor.length; j++) {
		giveColor[j].style.backgroundColor = arr2[j];
		}
	}
	randomColorOn(giveColor,color);	
</script>




  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值