Css Focus on input div appearing [duplicate]

和自甴很熟 提交于 2019-12-23 12:16:13

问题


I have such a code :

<div class="lighter">
  <form method="get" action="http://www.google.pl" id="search">
    <span>
      <input id="button_search" type="image" src="images/search.png" id="button_search"/>
    </span>
    <span>
      <input type="text" class="search rounded" placeholder="Search...">
    </span>
    <div class= "list_search">
      <ul>
        <li class="search_link"><a href="">Search all of Movies</a></li>
        <li class="search_link"><a href="">Advanced Search</a></li>
      </ul>
    </div>
  </form>
</div>

Is it possible simply using css to have an effect that when input type="text" is on focus list_search will appear? If yes, how?

Thanks a lot for help


回答1:


This is actually possible with pure CSS, if you are able to change your markup slightly.

div {
    background: #f0a;
    display: none;
    height: 200px;
    width: 200px; }

input:focus + div { display: block; }

What I essentially do, is that first hide the div, and when the input field has focus, the immediate next sibling matching div changes it's display mode to block.

For this to work, it must be the immediate next sibling, as you cannot travel up the DOM tree, so you need to unwrap your input field. from the span.

See my fiddle: http://jsfiddle.net/TheNix/U28sd/

EDIT:
The "adjacent selector" (+) should work in IE7 and up (although I think there might be some issues with asynchronously loaded content). Note that the element must come immediately after, so it's just not "next element that matches Y" but actually "the element immediately following X, IF it matches Y".

Some times, if you know the markup and you like to hack, you can "count" your way down. input + div + div would target the second div, for example (provided the markup exactly matches). Of course, I would not recommend it, as it would blow up at the slightest change in your markup, and would be a pain to maintain.

Read more on selectors here: http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors




回答2:


If you are using jQuery (which I strongly suggest if you are just starting out in JS)

$(':text').focus(function(e){
    $('.list_search').toggle();
}).blur(function(e){
    $('.list_search').toggle();
});


来源:https://stackoverflow.com/questions/13315419/css-focus-on-input-div-appearing

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