javascript事件處理的三種方式

問題描述:如何實現如下功能

單擊輸入框時,提示信息消失,輸入框背景變黃色,但在瀏覽器其他地方後輸入框顯示提示消息


<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級事件

使用DOM監聽,加載事件
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級事件

是使用標準的addEventListener方式和IE私有的attachEvent方式
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="請輸入名字";
        
    })
}


發佈了52 篇原創文章 · 獲贊 9 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章