提示:
1.随机数
2.定时器
//第一种方法:
//用css动画+js写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>闪烁的星星</title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
body{
background-color: #000;
}
span{
width: 30px;
height: 30px;
/* 星星图片的地址 */
background: url("aa.gif") no-repeat;
position: absolute;
background-size:100% 100%;
animation: flash 1s alternate infinite;
}
@keyframes flash{
0% { opacity: 0; }
100% { opacity: 1; }
}
span:hover{
transform: scale(3, 3) rotate(180deg)!important;
transition: all 1s;
}
</style>
</head>
<body>
<script>
window.onload=function(){
// 1. 求出屏幕的尺寸
var screenW = document.documentElement.clientWidth;
var screenH = document.documentElement.clientHeight;
// 2. 动态创建星星
for (var i = 0; i < 150; i++){
// 2.1 创建星星
var span = document.createElement('span');
document.body.appendChild(span);
// 2.2 随机的坐标
var x = parseInt(Math.random() * screenW);
var y = parseInt(Math.random() * screenH);
span.style.left = x + 'px';
span.style.top = y + 'px';
// 2.3 随机缩放
var scale = Math.random() * 1.5;
span.style.transform = 'scale(' + scale + ', ' + scale + ')';
// 2.4 频率
var rate = Math.random() * 1.5;
span.style.animationDelay = rate + 's';
}
}
</script>
</body>
</html>
//第二种方法:
//直接用js写
<style>
body {
background-color: black;
}
</style>
<script>
var num = 1;
function xingxing() {
var x = Math.floor(Math.random() * 1024);
var y = Math.floor(Math.random() * 768);
document.getElementById('one').innerHTML = `<div style="position: absolute;left:${x}px;top:${y}px;z-index: ${num};">
<img src="./xing.gif" width="30" height="30" alt="">
</div>`
x = Math.floor(Math.random() * 1024);
y = Math.floor(Math.random() * 768);
document.getElementById('two').innerHTML = `<div style="position: absolute;left:${x}px;top:${y}px;z-index: ${num};">
<img src="./xing.gif" width="30" height="30" alt="">
</div>`
x = Math.floor(Math.random() * 1024);
y = Math.floor(Math.random() * 768);
document.getElementById('three').innerHTML = `<div style="position: absolute;left:${x}px;top:${y}px;z-index: ${num};">
<img src="./xing.gif" width="30" height="30" alt="">
</div>`
x = Math.floor(Math.random() * 1024);
y = Math.floor(Math.random() * 768);
document.getElementById('four').innerHTML = `<div style="position: absolute;left:${x}px;top:${y}px;z-index: ${num};">
<img src="./xing.gif" width="30" height="30" alt="">
</div>`
x = Math.floor(Math.random() * 1024);
y = Math.floor(Math.random() * 768);
document.getElementById('five').innerHTML = `<div style="position: absolute;left:${x}px;top:${y}px;z-index: ${num};">
<img src="./xing.gif" width="30" height="30" alt="">
</div>`
num++;
setTimeout(xingxing,500);
}
</script>
</head>
<body onload="xingxing()">
<div id="one">
</div>
<div id="two">
</div>
<div id="three">
</div>
<div id="four">
</div>
<div id="five">
</div>
</body>