例子
| 代碼如下 |
複製代碼 |
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" class="input" onfocus="myFocus(this)" onblur="myBlur(this)" value="11">
<input type="text" class="input" onfocus="myFocus(this)" onblur="myBlur(this)" value="22">
</body>
</html>
<script>
function myFocus(element){
if (element.value == element.defaultValue){
element.focus();
element.value = '';
}
}
function myBlur(element){
if (element.value == ''){
element.blur();
element.value = element.defaultValue;
}
}
</script> |
補充:
onFocus事件就是當游標落在文字框中時發生的事件。
onBlur事件是游標失去焦點時發生的事件。
支援該事件的js對象
button, checkbox, fileUpload, layer, frame, password, radio, reset, select, submit,
text, textarea, window
當然我們也可以使用jquery來實現了,方法更簡單並且代碼也簡潔許多少。
| 代碼如下 |
複製代碼 |
|
$("#id").focus(function(){
……
});
與
$("input").blur(function(){
$("input").css("background-color","#D6D6FF");
}); |
例子
| 代碼如下 |
複製代碼 |
|
html
<input name="q" type="text" class="you" id="xf_search" value="11111">
jquery代碼
<script type="text/javascript">
(function (){ $("#xf_search").focus(function (){(this.value=='11111')?this.value='':false}); $("#xf_search").blur(function (){(this.value=='')?this.value='11111':false}); }());
</script> |
方法可以實現我們不在html表單上加js代碼這個從最佳化方面來講是有很大的提升哦