盒子内随机产生不同颜色方块

<!DOCTYPE html>

<html lang="en">

 

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

</head>

<style>

* {

padding: 0;

margin: 0;

list-style: none;

box-sizing: border-box;

}

 

#rect {

width: 400px;

height: 400px;

margin: 100px auto;

background: #000;

}

 

ul {

width: 400px;

height: 400px;

overflow: hidden;

}

 

li {

position: absolute;

width: 10px;

height: 10px;

background: #f00;

float: left;

}

</style>

 

<body>

<div id="rect">

<ul>

<li></li>

<li></li>

<li></li>

<li></li>

<li></li>

<li></li>

<li></li>

<li></li>

</ul>

</div>

</body>

<script>

 

// 实现效果

// 大盒子里面每隔一段时间就在不同的位置出现不同颜色小格子

 

// 思路:一开始加载就让多个小格子的位置不同,利用利用margin-lef和Math.random()

 

function init() {

// 1.0获取所有的li元素

var li = document.getElementsByTagName("li");

 

// 2.0利用for循环遍历小格子,循环里面进行逻辑代码编写

for (let i = 0; i < li.length; i++) {

 

// 2.1声明变量为产生10-390之间的数(这里是因为我自己设置大盒子width为400,height为400)

var a = Math.floor(Math.random() * 39 + 1) * 10;

var f = Math.floor(Math.random() * 39 + 1) * 10;

 

// 2.2颜色变量rgba在0~255之间,所以随机数设置为0~255

var b = Math.floor(Math.random() * 255);

var c = Math.floor(Math.random() * 255);

var d = Math.floor(Math.random() * 255);

 

// 透明度设置0~1

var e = Math.random();

// console.log(a); // console.log(b);

li[i].style.marginLeft = a + "px";

li[i].style.marginTop = f + "px";

 

// 随机透明度(随机透明度)

// li[i].style.backgroundColor = "rgba(" + b + "," + c + "," + d + "," + e + ")";

 

// 固定透明度(透明度设置1)

li[i].style.backgroundColor = "rgba(" + b + "," + c + "," + d + "," + 1 + ")";

}

}

 

// 定时器设置每个500毫秒就进行加载init()一次

setInterval(() => {

init();

}, 500);

init();

</script>

</html>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值