Version 1
CSS code part:
Copy the codeThe code is as follows:
.focus {
border: 1px solid #f00;
background: #fcc;
}
When the focus is obtained, add focus style, add borders, and change the background color to #fcc
html code part:
Copy the codeThe code is as follows:
<body>
<form action="" method="post" >
<fieldset>
<legend>Personal Basic Information</legend>
<div>
<label for="username">Name:</label>
<input type="text" />
</div>
<div>
<label for="pass">Password:</label>
<input type="password" />
</div>
<div>
<label for="msg">Details:</label>
<textarea rows="2" cols="20"></textarea>
</div>
</fieldset>
</form>
</body>
Here are two inputs and a textare box.
:input matches all input, textarea, select and button elements.
jQuery code part:
Copy the codeThe code is as follows:
<script type="text/javascript">
$(function(){
$(":input").focus(function(){
$(this).addClass("focus");
}).blur(function(){
$(this).removeClass("focus");
});
})
</script>
Use :input to match all input elements. When obtaining focus, add style focus to automatically identify the current element through $(this). The focus() method is to get the function executed when the focus event occurs. The blur() method is a function executed when the event loses focus occurs.
Version 2:
Sometimes there is a default content in the text box as a prompt message. After obtaining the focus, it needs to disappear. The following modifications can be made:
Copy the codeThe code is as follows:
<script type="text/javascript">
$(function(){
$(":input").focus(function(){
$(this).addClass("focus");
if($(this).val() ==){
$(this).val("");
}
}).blur(function(){
$(this).removeClass("focus");
if ($(this).val() == '') {
$(this).val();
}
});
})
</script>
Make a logical judgment. If the value is the default value, clear the content in the text box.
Lost focus, if the text box is empty, that is, there is no input, the value is set to the default value.
This is a simple logic.