JavaScript進階——事件監聽控制,javascript事件監聽
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>事件監聽 </title><script type="text/javascript">function run(){ alert("你好");}/* onfocus元素擷取焦點onblur元素失去焦點 */ function run1() { alert("擷取焦點"); } function run2() { alert("失去焦點"); } /* onload 頁面載入完成時執行。。。可以有效避免 使用元素標籤時/擷取元素對象時 元素未載入 */ function run3() { alert(document.getElementById("HH").innerHTML); } /* onchange() 當值改變時調用 */ function run4() { alert("選擇的值改變了"); } /* javascript 事件綁定方式 1、HTML 屬性綁定方式2、HTML DOM 方法綁定 */ function run5() { var arr = document.getElementsByTagName("input");alert(arr.length);alert(arr[0].value); } function run6(x) { alert(x.value); } /* 如果輸入數字 允許存取如果輸入非數字 阻止預設事件(鍵盤輸入鍵碼值事件)0~9 鍵碼值 48~57 8對應退格鍵 */ function run7() { //擷取事件對象 var e = window.event;//擷取鍵碼值進行判斷var code = e.keyCode;if(!(code)>=48 && code<=57){ // 不是數字 阻止預設事件e.returnValue = false;} } function run8(e) { //擷取鍵碼值 var code; if(e&&e.preventDefault){ //Firefox或者其他瀏覽器 code=e.which; }else{ //IE code=window.event.keyCode; } //通過鍵碼值進行判斷 !(48~57) 非數字 並且 不是退格鍵 8 if(!((code>=48 && code<=57)||(code==8))){ //阻止預設事件 if(e&&e.preventDefault){ //Firefox或者其他瀏覽器 e.preventDefault(); }else{ //IE window.event.returnValue=false; } } }</script></head><body onload="run3()"><input type="button" value="我是按鈕 " onclick="run()" /><input type="text" onfocus="run1()" onblur="run2()" /><span id="HH">body啟動</span><select onchange="run4()"><option value="bj">北京</option><option value="sh">上海</option><option value="sz">深圳</option></select><p></p><input type="button" value="按鈕1" onclick="run5()" /><input type="button" value="按鈕2" onclick="run6(this)" /><!-- ------------------------------------------------- --><input type="text" id="i1" onkeydown="run7()" /><br/><input type="text" id="i2" onkeydown="run8(event)" /><br/></body></html>
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。