这里主要就是利用浏览器的视口宽高(网页可视区的宽高)来实现
大致思路如下:
1.搭架子
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
background: #000;
overflow: hidden;
}
span {
display: inline-block;
width: 30px;
height: 30px;
background: url("images/star.png") no-repeat;
background-size: 100% 100%;
animation: flash 1s alternate infinite;
position: absolute;
}
@keyframes flash {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
span:hover {
transform: scale(3, 3) rotate(180deg) !important;
transition: all 1s;
}
<span></span>
2.动态创建
首先就要删除上面的html结构里的span
具体步骤:
1.获取网页可视区的宽高
2.动态创建小星星,
- 创建小星星
- 随机小星星的位置
- 随机小星星的缩放比例
- 随机显示/隐藏动画
//1.获取网页可视区的宽高
let {
width,
height
} = getScreen();
//2.动态创建小星星
for (let i = 0; i < 200; i++) {
//1.创建小星星
let oSpan = document.createElement("span");
document.body.appendChild(oSpan);
//2.随机小星星的位置
let x = Math.random() * (width - 30);
let y = Math.random() * (height - 30);
oSpan.style.left = x + 'px';
oSpan.style.top = y + 'px';
//3.随机小星星的缩放比例
let scale = Math.random() * 2;
oSpan.style.transform = `scale(${scale},${scale})`;
//4.随机显示/隐藏动画
let time = Math.random() * 2;
oSpan.style.animationDelay = time + 's';
}
function getScreen() {
let width, height;
if (window.innerWidth) {
width = window.innerWidth;
height = window.innerHeight;
} else if (document.compatMode === "BackCompat") {
width = document.body.clientWidth;
height = document.body.clientHeight;
} else {
width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
}
return {
width: width,
height: height
}
}