我正在尝试仅使用 CSS/HTML 实现带有下拉建议的搜索框。它显示正常,但我无法在单击下拉元素时触发 onclick 事件,并且链接也不起作用。如果我不隐藏列表,那么它可以正常工作,但是当使用输入框的“:focus”选择器隐藏然后显示时,它不再对点击使用react。
知道如何解决这个问题吗?这是隐藏元素的正常行为吗?
它基于this example ,它似乎也在那里不起作用。
重现问题的简单示例:
HTML:
<html>
<head>
<link rel="stylesheet" href="test.css" />
</head>
<input class="inputfield" type="text" placeholder="SEARCH...">
<ul class="search-results">
<li class="typeahead" onclick="console.log('test')">
<a class="center" href="/test" >test</a>
</li>
<li class="typeahead" onclick="console.log('test')">
<a class="center" href="/test" >test</a>
</li>
<li class="typeahead" onclick="console.log('test')">
<a class="center" href="/test" >test</a>
</li>
<li class="typeahead" onclick="console.log('test')">
<a class="center" href="/test" >test</a>
</li>
</ul>
</html>
CSS:
input{
width: 300px;
height: 26px;
padding-left: 10px;
border: 1px solid lightgrey;
outline: none;
}
ul{
list-style-type: none;
padding: 0;
margin: 0;
visibility: hidden;
}
input:focus + ul{
visibility: visible;
}
li{
border: 1px solid lightgrey;
border-top-style: none;
width: 300px;
height: 25px;
padding-left: 10px;
background: #fff;
cursor: pointer;
}
li:hover{
background-color: lightgrey;
}
li:hover a{
color: white;
}
a{
color: black;
font-size: 12px;
display: block;
text-decoration: none;
}
最佳答案
问题是触发器的顺序,如 CeritT 的回答。
我的建议是使用transition
让ul
不会立即消失,从而允许点击它。
ul.search-results {
list-style-type: none;
padding: 0;
margin: 0;
visibility: hidden;
transition: visibility 0.2s;
}
关于HTML/CSS 下拉输入 onclick 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25198996/