問題描述:如何實現如下功能
單擊輸入框時,提示信息消失,輸入框背景變黃色,但在瀏覽器其他地方後輸入框顯示提示消息
<body>
<input type="text" id="name" value="請輸入名字" >
<button type="button" id="bt" >提交</button>
</body>
第一種:HTML處理事件
<body>
<input type="text" id="name" value="請輸入名字" οnfοcus="fun(this)" οnblur="fun1(this)" >
<button type="button" id="bt" >提交</button>
</body>
var a = document.getElementById("name");
function fun (x) {
if(a.value=="請輸入名字"){
a.value="";
x.style.background="yellow";
}
}
function fun1(x){
if(a.value == ""){
a.value = "請輸入名字";
x.style.background="white";
}
x.style.background="white";
}
第二種:DOM0級事件
var a = document.getElementById("name");
a.onfocus = function(){
if(a.value=="請輸入名字"){
a.value="";
this.style.background="yellow";
}
}
a.onblur = function(){
if(a.value == ""){
a.value = "請輸入名字";
this.style.background="white";
}
this.style.background="white";
}
第三種:DOM2級事件
var a = document.getElementById("name");
if(a.addEventListener){
a.addEventListener("focus",function(){
if(a.value=="請輸入名字"){
a.value="";
this.style.background="yellow";
}
})
a.addEventListener("blur",function(){
a.value="請輸入名字";
this.style.background="white";
})
}else{
a.attachEvent("onfocus",function(){
if(a.value=="請輸入名字"){
a.value="";
}
})
a.attachEvent("onblur",function(){
a.value="請輸入名字";
})
}