0%

css 自幹 autocomplete

autocomplete

因為要做搜尋功能 , 又覺得預設的搜尋很難用 , 專案也比較老 , 不太有套件可以直接插上去
所以決定自幹看看 , 比較特別的點就是希望可以在 inputfocus 狀態下 , 點到的選項才顯示
然後就踩到雷 , 如果沒加上 active 這個狀態的話 , 點下去就直接失去 focus
另外自訂自己的 autocomplete 預設 chrome 會在 input 送你之前搜尋過的東西 , 所以要設定 autocomplete="off"
code 老樣子還是沙雕沙雕的 style

See the Pen CSS Auto Complete by weber87na (@weber87na) on CodePen.

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
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Document</title>
<style>
input{
position: relative;
}
input::before{
position: absolute;
width: 100%;
height: 100%;
border-radius: 39%;
border: 1px solid;
content: '';
}

.autocomplete{
width: 300px;
height: 300px;
border: 1px solid;
display: none;
position: relative;
border-radius: 46%;
}
.autocomplete::before{
content: '';
width: 300px;
height: 300px;
border-radius: 36%;
top: -5px;
right: 12px;
border: 1px solid;
position: absolute;
}

/* 這裡重點需要加上 .autocomplete:active, 不然 btn click 沒辦法被 trigger */
.autocomplete:active,
#qq:focus + #test:checked ~ .autocomplete{
display: block;
}

#btn{
height: 50px;
width: 50px;
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}

</style>
</head>
<body>
<input type="text" id="qq">

<!--用 radio 的重點就是 name 要一樣-->
<input type="radio" name="test" id="test" checked>
<input type="radio" name="test" id="test2">
<input type="radio" name="test" id="test3">

<label for="test">test</label>
<label for="test2">test2</label>
<label for="test3">test3</label>

<div class="autocomplete">
<button id="btn">沙雕</button>
</div>

<script>
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
console.log('123')
});
</script>
</body>
</html>
關閉