JavaScript常用事件
除了剛才提到的 onclick 事件,還有這些常用的事件:
onclick 單擊
ondblclick 雙擊
onfocus 元素獲得焦點(diǎn)
onblur 元素失去焦點(diǎn)
onmouseover 鼠標(biāo)移到某元素之上
onmouseout 鼠標(biāo)從某元素移開(kāi)
onmousedown 鼠標(biāo)按鈕被按下
onmouseup 鼠標(biāo)按鍵被松開(kāi)
onkeydown 某個(gè)鍵盤(pán)按鍵被按下
onkeyup 某個(gè)鍵盤(pán)按鍵被松開(kāi)
onkeypress 某個(gè)鍵盤(pán)按鍵被按下并松開(kāi)
其中,onmouseover 和 onmouseout 事件可用于在鼠標(biāo)移至 HTML 元素上和移出元素時(shí)觸發(fā)函數(shù)。比如這一例子:
<html> <head></head> <body> <div style="background-color:green;width:200px;height:50px;margin:20px;padding-top:10px;color:#ffffff;font-weight:bold;font-size:18px;text-align:center;" onmouseover="this.innerHTML='good'" onmouseout="this.innerHTML='you have moved out'" >move your mouse to here</div> </body> </html>
鼠標(biāo)移入時(shí),顯示“good”,鼠標(biāo)移出時(shí)顯示“you have moved out”:
onmousedown, onmouseup 是鼠標(biāo) 壓下 和 松開(kāi) 的事件。首先當(dāng)點(diǎn)擊鼠標(biāo)按鈕時(shí),會(huì)觸發(fā) onmousedown 事件,當(dāng)釋放鼠標(biāo)按鈕時(shí),會(huì)觸發(fā) onmouseup 事件。舉例說(shuō)明:
<html> <head> <script> function mDown(obj) // 按下鼠標(biāo) 的 事件處理程序 { obj.style.backgroundColor="#1ec5e5"; obj.innerHTML="release your mouse" } function mUp(obj) // 松開(kāi)鼠標(biāo) 的 事件處理程序 { obj.style.backgroundColor="green"; obj.innerHTML="press here" } </script> </head> <body> <div style="background-color:green;width:200px;height:35px;margin:20px;padding-top:20px;color:rgb(255,255,255);font-weight:bold;font-size:18px;text-align:center;" onmousedown="mDown(this)" onmouseup="mUp(this)" >press here</div> </body> </html>
運(yùn)行結(jié)果可見(jiàn),按下鼠標(biāo)時(shí),顯示“release your mouse”,背景變?yōu)樗{(lán)色;松開(kāi)鼠標(biāo)后,顯示為“press here”,背景變?yōu)榫G色。