Home >Web Front-end >JS Tutorial >Text box input focus and defocus style implementation code_javascript skills

Text box input focus and defocus style implementation code_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:49:071961browse

First, use the css pseudo-class: focus can be changed.

The html code of the text box is assumed to be as follows:

Copy code The code is as follows:


Name:


Password :


Textarea:

< textarea>




css code is written like this:

input[type="text" ]:focus, input[type="password"]:focus, textarea:focus { border: 1px solid #f00; background: #ccc; }
The text box, password box, and paragraph box are listed respectively. The style of the three input boxes when they are focused. Add a red border and gray background.

Is it that simple to solve now? Use a browser (Firefox, Safari, IE7) to test, everything is ok, but IE6 is not supported.

If you want IE6 to have the same beautiful effect, you can only use js. Here I use jquery to make one for you. Effect.
Copy code The code is as follows:

$(document).ready(function(){
$("input[@type='text'], input[@type='password'], textarea").focus( function(){ $(this). css({background:"#ccc", border:"1px solid #f00"})} );
});

Isn’t it very simple to make jquery? It feels similar to the way of writing css!

This is just the focus state. The out-of-focus state of jquery requires you to give instructions. It is silly and naive. It will not change back by itself, so then add the out-of-focus state.
Copy code The code is as follows:

$(document).ready(function(){
$("input[@type='text'], input[@type='password'], textarea").focus(function(){$(this).css({background:"#ccc", border: "1px solid #f00"})}).blur(function(){$(this).css({background: “#FFF”, border: “1px solid #ccc”})});
})

After defocusing, the background edge becomes white and the border becomes gray.

Of course you can also use jquery's addClass and removeClass to simplify the code:
Copy the code The code is as follows:

$(document).ready(function(){
$("input[@type='text'], input[@type='password'], textarea").focus (function(){$(this).addClass("focus")}).blur(function(){$(this).removeClass("focus")});
})

First give the input box a default style. When it is focused, use addClass to add css "focus". When it is out of focus, use removeClass to remove css "focus".

All done!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn