先看图:
大致思路:
根据当前浏览器大小,用setInterval()函数每隔一定时间创建一个随机的div,并设置div的样式。
具体步骤:
1、将随机生成的div定位。
* {
margin: 0;
padding: 0;
}
div {
position: absolute;
}
2、用setInterval()函数每隔一定时间创建一个div和删除按钮。
start = setInterval(function() {
let getDiv = document.createElement("div");
let del = document.createElement("span");
}, 100)
3、设置div和按钮的样式。
//del删除按钮样式
del.innerText = "×";
del.style.position = "absolute";
del.style.right = "0";
del.style.cursor = "pointer";
//div样式
let wid = getRandom(100, 150);//调用随机生成数函数getRandom()设置宽高
let hig = getRandom(100, 150);//调用随机生成数函数getRandom()设置宽高
getDiv.style.width = wid + "px";
getDiv.style.height = hig + "px";
getDiv.style.left = getRandom(0, window.innerWidth - wid) + "px";//调用随机生成数函数getRandom()设置位置
getDiv.style.top = getRandom(0, window.innerHeight - hig) + "px";//调用随机生成数函数getRandom()设置位置
let color = "#" + getRandom(0, 16777215).toString(16);//将随机生成的数转成16进制
getDiv.style.backgroundColor = color;
getDiv.style.opacity = Math.random();//透明度
//生成随机数函数
function getRandom(min, max) {
let res = Math.abs(max - min);
return Math.floor(Math.random() * (res + 1)) + min;
}
4、将生成的div加入到body中。
getDiv.appendChild(del);//将删除按钮加入到div中
document.body.appendChild(getDiv);//将div加入到body中
5、实现删除按钮功能。
//给按钮添加单击事件,单击删除其父节点
del.onclick = function() {
document.body.removeChild(this.parentNode);
}
6、为了友好显示,设置一个计数器,并到一定数量时清除间隔期。
if (count == 50) {
clearInterval(start);
}
所有代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
div {
position: absolute;
}
</style>
</head>
<body>
<script>
let start;
let count = 0;
let randomX, randomY;
//console.log(window.innerHeight + " : " + window.innerWidth);
start = setInterval(function() {
let randomX, randomY;
let getDiv = document.createElement("div");
let del = document.createElement("span");
del.innerText = "×";
del.style.position = "absolute";
del.style.right = "0";
del.style.cursor = "pointer";
//给按钮添加单击事件,单击删除其父节点
del.onclick = function() {
document.body.removeChild(del.parentNode);
}
let wid = getRandom(100, 150);
let hig = getRandom(100, 150);
getDiv.style.width = wid + "px";
getDiv.style.height = hig + "px";
getDiv.style.left = getRandom(0, window.innerWidth - wid) + "px";
getDiv.style.top = getRandom(0, window.innerHeight - hig) + "px";
let color = "#" + getRandom(0, 16777215).toString(16);
getDiv.style.backgroundColor = color;
getDiv.style.opacity = Math.random();
//添加按钮到div中
getDiv.appendChild(del);
//添加div到body中
document.body.appendChild(getDiv);
count++;
if (count == 500) {
clearInterval(start);
}
function getRandom(min, max) {
let res = Math.abs(max - min);
return Math.floor(Math.random() * (res + 1)) + min;
}
}, 100)
</script>
</body>
</html>