前端切图学习-按键代码展示

Event KeyCode

Posted by R1NG on August 31, 2021 Viewed Times

按键代码展示 Event KeyCode

1. 概述

项目本体为一个可以实时展示按下按钮类型和按钮对应代码的网页.

效果:

20210901150418


2. 结构和切图

网页的基本结构如下:

1
2
3
4
5
6
7
<body>
    <div id="insert">
        <div class="key">
            Press any key to get the KeyCode
        </div>
    </div>
</body>


3. 编写 CSS 样式

首先将 body 的样式设为 水平垂直居中:

1
2
3
4
5
6
7
8
9
10
11
body {
    background-color: #999999;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    height: 100vh;
    overflow: hidden;
    margin: 0;
}

然后设定每一个子容器和提示文字的样式. 此处对应的提示文字采用相对子容器本身的绝对定位, 并采用竖向排列布局方式.

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
.key {
    border: 1px solid #e1e1e1;
    background-color: #eee;
    box-shadow: 1px 1px 3px rgba(0, 0, 0, .3);
    display: inline-flex;
    align-items: center;
    font-size: 20px;
    font-weight: 300;
    padding: 20px;
    flex-direction: column;
    margin: 10px;
    min-width: 150px;
    position: relative;
}
.key small {
    position: absolute;
    top: -24px;
    left: 0;
    text-align: center;
    width: 100%;
    color: #085ac5;
    font-size: 14px;
    font-weight: 600;
    text-transform: uppercase;   
}

完整的 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
35
36
37
38
39
* {
    box-sizing: border-box;
}
body {
    background-color: #999999;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    height: 100vh;
    overflow: hidden;
    margin: 0;
}
.key {
    border: 1px solid #e1e1e1;
    background-color: #eee;
    box-shadow: 1px 1px 3px rgba(0, 0, 0, .3);
    display: inline-flex;
    align-items: center;
    font-size: 20px;
    font-weight: 300;
    padding: 20px;
    flex-direction: column;
    margin: 10px;
    min-width: 150px;
    position: relative;
}
.key small {
    position: absolute;
    top: -24px;
    left: 0;
    text-align: center;
    width: 100%;
    color: #085ac5;
    font-size: 14px;
    font-weight: 600;
    text-transform: uppercase;   
}


4. JavaScript

最后编写 JavaScript 函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
const insert = document.getElementById('insert');

window.addEventListener('keydown', (e) => {
    insert.innerHTML = `
    <div class="key">
        ${e.key == ' '? 'Space' : e.key}
        <small>event.key</small>
    </div>
    <div class="key">
        ${e.code}
        <small>event.code</small>
    </div>`
})

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