44.夜空中的星星

需求:黑夜,无数不同位置的星星闪烁,hover星星放大,转动180度

实现黑夜

黑夜利用 background: #000;,占满屏幕

1
2
3
4
5
6
html,body{
width: 100%;
height: 100%;
background: #000;

}

一颗星星放大闪烁

布局一颗星星,用span标签代表一颗星星,后面用js创建随机位置的星星

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
   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);
transition: all 1s;
}

<span></span>

放大旋转利用 transform: scale(3, 3) rotate(180deg)

不断闪烁利用:animation: flash 1s alternate infinite;

不同位置及大小的星星

给span设置position: absolute;,在生成的span中设置left,top,但left,top大小必须在网页范围

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 2.创建星星
for(let i = 0; i < 200; i++){
// 1.添加星星
let oSpan = document.createElement("span");
document.body.appendChild(oSpan);
// 2.随机位置
let x = Math.random() * width;
let y = Math.random() * height;
oSpan.style.left = x + "px";
oSpan.style.top = y + "px";
// 3.随机缩放
let scale = Math.random() * 2;
oSpan.style.transform = `scale(${scale}, ${scale})`
// 4.随机动画延迟
let rate = Math.random() * 2;
oSpan.style.animationDelay = rate + "s";
}
  1. 小问题:有时候会出现滚动条,为什么?不是x,y都是可视区吗?是因为加上小星星的30px就超出了,所以解决方式有两种:
  • 给body设置overflow: hidden;

  • Math.random() * width;`减掉30px

  1. 利用let scale = Math.random() * 2;实现随即大小的星星

  2. 还有个小问题,hover后没有旋转变大?是因为transform:优先级不够高

,加上!important解决

44.夜空中的星星