夺命雷公狗---javascript NO:08 常用的事件
常用的事件
onLoad :当页面载入完毕时触发,常用于body元素
lonUnload :当页面卸载时(关闭时)触发,常用于body元素
lonBlur :失去焦点时触发
lonFocus :获得焦点时触发
lonClick :单击时触发
lonMouseOver :鼠标悬浮时触发
lonMouseOut :鼠标离开时触发
lonMouseDown :鼠标按下时触发
lonMouseUp :鼠标弹起时触发
lonMouseMove :鼠标移动时触发
lonChange :状态改变时触发,常用于select
lonSelect :内容选中时触发
lonkeypress :键盘点击时触发
lonkeydown :键盘按下时触发
lonkeyup :键盘弹起时触发
lonSubmit :表单提交时触发,常用于form表单元素
lonReset :表单重置时触发,常用于form表单元素
示例代码:
例1:onload(当页面载入完毕时触发)与onunload(当页面卸载时(关闭时)触发)
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> <script> function fun1(){ alert(‘页面载入时触发’); } function fun2(){ alert(‘页面关闭时触发’); } </script> </head> <body onload=fun1();onunload=fun2();></body> </html>
例2:onblur(失去焦点时触发)与onfocus(获得焦点时候触发)
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> <script> function fun1(){ document.getElementById(‘username’).value; } function fun2(){ document.getElementById(‘tip’).innerHTML = ‘用户名不能为空'; } </script> </head> <body> <input type=”text” id=’username’ name=”username” value=”请输入用户名” onfocus=”fun1()”; onblur=”fun2();”><span id=’tip’></span> </body> </html>
例3:onmouseover(鼠标浮动时触发)与onmouseout(鼠标离开时触发)
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> <script> function fun1(){ document.getElementById(‘test’).innerHTML += ‘鼠标浮动<br/>'; } function fun2(){ document.getElementById(‘test’).innerHTML += ‘鼠标离开<br/>'; } </script> </head> <body> <img src=”1.jpg” onmouseover=”fun1();” onmouseout=”fun2();” /> <div id=”test”></div> </body> </html>
例4:onchange(状态改变时候触发,常用于select)
示例:
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> </head> <body> <select id=”shengfen” onchange=”fun1();”> <option>请选择省份</option> </select> <script> var sheng = [‘广东’,’河北’,’湖南’,’福建’,’广西’,’山东’]; for(var i in sheng){ var op = new Option(sheng[i]); document.getElementById(‘shengfen’).options.add(op); } function fun1(){ alert(‘状态改变了’); } </script> </body> </html>
例5:onsubmit(表单提交时触发)
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> <script> function fun1(){ alert(“相关数据不能为空”); return false; } </script> </head> <body> <form method=”post” action=”” onsubmit=”return fun1();”> <input type=”submit” name=”submit” value=”提交”> </form> </body> </html>