搜索框
wenking 8/28/2023 通用组件
当我们在使用文本域的时候,如果内容超过了文本域的高度,那么将出现滚动条,这个在搜索框是不被期望的,这个样式可以通过js实现
const textarea = document.querySelector('#search');
textarea.addEventListener("input", function (e) {
// 如果不写改行,哪么删除之前的内容,文本域不会缩小
this.style.height = 'auto';
// 设置文本域的高度等于内容的总高度
this.style.height = e.target.scrollHeight + 'px';
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.main {
width: 1200px;
margin: 0 auto;
text-align: center;
}
.search-form {
width: 480px;
padding: 5px 0;
margin: 20px auto;
border: 2px solid transparent;
border-radius: 10px;
position: relative;
text-align: left;
}
#search {
resize: none;
font-size: 24px;
border: none;
margin-left: 10px;
}
#search:focus {
outline: none;
}
#search-btn {
width: 80px;
border: none;
font-size: 18px;
background-color: #ffc107;
height: 27px;
position: absolute;
}
.search-form:has(#search:focus) {
border: 2px solid rgba(0, 0, 0, 0.3);
}
</style>
</head>
<body>
<div class="main">
<img height="100" width="300"
src="https://www.google.com.hk//images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt=""/>
<div class="search-area">
<form class="search-form" action="">
<label for="search"></label>
<textarea name="search" id="search" cols="30" rows="1"></textarea>
<input type="submit" id="search-btn" value="搜索"/>
</form>
</div>
</div>
</body>
<script>
const textarea = document.querySelector('#search');
textarea.addEventListener("input", function (e) {
this.style.height = 'auto';
this.style.height = e.target.scrollHeight + 'px';
})
const searchBtn = document.querySelector("#search-btn");
searchBtn.addEventListener("click", function (e) {
e.preventDefault();
alert(textarea.value);
textarea.value = "";
})
textarea.addEventListener("keydown", function (e) {
if (e.keyCode == 13) {
searchBtn.click();
e.preventDefault();
}
})
</script>
</html>
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99