前端切图学习-七彩悬浮板

Hoverboard

Posted by R1NG on September 1, 2021 Viewed Times

七彩悬浮板 Hoverboard

1. 概述

项目本体展示了一个悬浮板, 光标触及的正方形子板会随机点亮为不同的颜色.

效果:

20210902134916


2. 结构和切图

网页的基本结构极其简单:

1
2
3
<body>
    <div class="container" id="container"></div>
</body>

每一个具体的正方形子板都是有 JavaScript 函数添加的.


3. 编写 CSS 样式

body 的排版方式设为水平垂直居中:

1
2
3
4
5
6
7
8
9
body {
  background-color: #111;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  margin: 0;
}

然后控制容纳正方形子板的容器的最大宽度:

1
2
3
4
5
6
7
.container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  max-width: 400px;
}

最后设定子板本身的样式, 令其在鼠标悬浮于其上时立刻点亮:

1
2
3
4
5
6
7
8
9
10
11
12
.square {
  background-color: #1d1d1d;
  box-shadow: 0 0 2px #000;
  height: 16px;
  width: 16px;
  margin: 2px;
  transition: 2s ease;
}

.square:hover {
  transition-duration: 0s;
}

完整的 CSS 样式表如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
* {
  box-sizing: border-box;
}

body {
  background-color: #111;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  margin: 0;
}

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  max-width: 400px;
}

.square {
  background-color: #1d1d1d;
  box-shadow: 0 0 2px #000;
  height: 16px;
  width: 16px;
  margin: 2px;
  transition: 2s ease;
}

.square:hover {
  transition-duration: 0s;
}


4. JavaScript

最后, 我们编写 JavaScript 函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const container = document.getElementById('container');
const colors = ['#e74c3c', '#8e44ad', '#3498db', '#e67e22', '#2ecc71'];
const SQUARES = 500;

for (let i=0; i<SQUARES; i++) {
    const square = document.createElement('div');
    square.classList.add('square');
    square.addEventListener('mouseover', () => setColor(square));
    square.addEventListener('mouseout', () => removeColor(square));
    container.appendChild(square);
}

function setColor(element) {
    const color = getRandomColor();
    element.style.background = color
    element.style.boxShadow = `0 0 2px ${color}, 0 0 10px ${color}`;
}

function removeColor(element) {
    element.style.background = '#1f1e33';
    element.style.boxShadow = '0 0 2px #000';
}

function getRandomColor() {
    return colors[Math.floor(Math.random() * colors.length)];
}

注意此处对每一个正方形子板事件的监听.

最后, 完整的网页演示可见 此处