简体   繁体   中英

How to style a form element when an input is focused?

I have a form that is structured similarly to the one below. How do I use CSS to style the input[type=submit] element when the input[type=text] is focused?

For example:

<form id="example">
    <input type="text" name="search">
    <input type="submit" value="Search">
</form>

<style>
    #example > input[type="text"]:focus {
        // please style input[type="submit"]
    }
</style>

I'm trying to accomplish this because a wordpress theme has a search form with the search input and submit button inline. When a user focuses on the input, I want the input field and submit button to have the same border color change.

Alternatively, I could style the entire div around the input and submit button, but then we come back to the problem of styling another element when one element is focused.

Is this even possible with CSS3 or would I have to resort to a javascript function? (Last resort.)

If the structure in your actual code is the same as what you've posted in question, you can use + (adjacent) selector to select the submit button when there's focus on text input.

This is the selector you're looking for: #example > input[type="text"]:focus + input[type="submit"]

To read more about + selector, this answer to "What does the “+” (plus sign) CSS selector mean?" explains it in a short manner and even covers browser support.


Here is a snippet to show it in action. Doesn't look too pretty, but does the job :)

 #example > input[type="text"]:focus + input[type="submit"] { background: gray; } 
 <form id="example"> <input type="text" name="search"> <input type="submit" value="Search"> </form> 

Here is a way using JQuery, see fiddle https://jsfiddle.net/t33rdra6/2/

  $(document).ready(function() {

    $('input').blur(function() {
        $('input[type="submit"]').removeClass("focus")
      })
      .focus(function() {
        $('input[type="submit"]').addClass("focus");
      });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM