HTML/CSS Dropdown input onclick not firing

风流意气都作罢 提交于 2019-12-11 09:54:27

问题


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.



来源:https://stackoverflow.com/questions/25198996/html-css-dropdown-input-onclick-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!