话不多说直接代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
/*溢出隐藏*/
/*解决塌陷*/
/*清除浮动*/
}
div{
position: absolute;
border-radius: 50%;
}
</style>
</head>
<body>
<!--生成100个小圆,大小随机,位置随机,颜色随机,透明度随机-->
<!--让圆闪烁起来-->
</body>
<script>
for (var i=0; i<40; i++) {
var d = document.createElement("div");
var cm = rand(10,150);
d.style.width = cm + 'px';
d.style.height = cm + 'px';
d.style.left = rand(0,window.innerWidth-150) + 'px';
d.style.top = rand(0,window.innerHeight-150) + 'px';
var r = rand(0,255);
var g = rand(0,255);
var b = rand(0,255);
var color = `rgb(${r},${g},${b})`;
d.style.backgroundColor = color;
var op = Math.random();
d.style.opacity = op;
// 手动为div创造一个属性speed
d.speedOpacity = 0.01;
if (0.5 - Math.random() > 0) {
d.speedOpacity = -0.01;
}
d.speedX = rand(2,4);
if (0.5 - Math.random() > 0) {
d.speedX *= -1;
}
d.speedY = rand(2,4);
if (0.5 - Math.random() > 0) {
d.speedY *= -1;
}
document.body.appendChild(d);
}
function rand(min,max) {
return Math.round(Math.random() * (max-min) + min);
}
function changeOpacityAndPosition() {
var ds = document.getElementsByTagName("div");
for (var i=0; i<ds.length; i++) {
var d = ds[i];
var op = d.style.opacity;
op = parseFloat(op);
op += d.speedOpacity;
if (op>=1 || op <= 0) {
d.speedOpacity *= -1;
}
d.style.opacity = op;
var x = d.offsetLeft + d.speedX;
var y = d.offsetTop + d.speedY;
if (x < 0) {
x = 0;
d.speedX *= -1;
} else if (x > window.innerWidth-d.offsetWidth) {
x = window.innerWidth-d.offsetWidth;
d.speedX *= -1;
}
if (y < 0) {
y = 0;
d.speedY *= -1;
} else if (y > window.innerHeight-d.offsetHeight) {
y = window.innerHeight-d.offsetHeight;
d.speedY *= -1;
}
d.style.left = x + 'px';
d.style.top = y + 'px';
}
}
setInterval(function(){
changeOpacityAndPosition()
},30);
</script>
</html>
<!--relative:不会影响元素本身的特性,定位参考是原来的位置
absolute: 脱离文档流,找最近的使用了定位的父级来定位,如果没有找body
fixed: 脱离文档流,找窗口定位-->
可以通过改变i的值来改变气泡个数。目前定义的是40
个人觉得挺好看的,电脑闲置的时候可以把整个网页打开,然后F11全屏,作为桌面背景。
还有,由于是网页所以不能直接做成桌面背景,有人说可以截图,截成视频,拜托这些完全是随机的,弄成视频就不是随机的了好吧-_-!。当然如果你有什么办法把网页做成桌面背景,欢迎给我留言。
还有本次代码是本校实训时的成果,并不是完全靠个人做出来的。如有雷同,不胜惶恐!
作者:Lee_1310
来源:CSDN
原文:https://blog.csdn.net/Lee_1310/article/details/89048898
版权声明:本文为博主原创文章,转载请附上博文链接!