HTML/CSS Dropdown input onclick not firing

2019-08-07 05:33发布

问题:

I am trying to implement an search box with dropdown suggestions using CSS/HTML only. It displays fine but I cannot get the onclick event to fire when clicking on a dropdown element and the links don't work either. If I don't hide the list then it works fine, but when hidden and then displayed using the ":focus" selector of the input box it does not react to clicks anymore.

Any idea how to fix this? Is this a normal behavior for hidden elements?

It is based on this example, and it does not seem to work there either.

A simple example reproducing the problem:

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;
}

回答1:

The problem is the order of the triggers, as in CeritT's answer.

My suggestion is to use transition to make ul to not disappear immediately, thus allow clicking on it.

ul.search-results {
    list-style-type: none;
    padding: 0;
    margin: 0;
    visibility: hidden;
    transition: visibility 0.2s;
}


回答2:

The problem is the order of triggers, focus, blur and click;

'search-results' is visible when input gets focused, so it is hidden when input is not focused. When you click on a 'li', input loses its focus and 'li' dissappears before the click event is triggered.

One solution is to change onclick to onmousedown.