第七章 异步编码
1 事件处理程序
处理程序:即网页加载完毕后将执行的代码,称回调函数或监听器;
包含:处理函数+window.onload=函数名;
<script language="JavaScript" type="text/JavaScript"> function page(){ alert("I'm alive!"); } window.onload=page; </script>
2 响应事件的方式编写代码
getElementByTagName返回NodeList对象,
表示DOM事件对象的属性:
target:存储触发事件的对象;
type:是字符串,如("click","load")指出发生的是哪种事件
timeStamp:提供事件发生时间属性;
keyCode:告诉用户刚刚按下那个键
clientX:确定鼠标/单击位置离浏览器窗口左边缘有多远;
clientY:确定鼠标/单击位置离浏览器窗口上边缘有多远;
screenX:确定鼠标/单击位置离屏幕窗口左边缘有多远;
screenY:确定鼠标/单击位置离屏幕窗口上边缘有多远;
pageX:确定鼠标/单击位置离网页窗口左边缘有多远;
pageY:确定鼠标/单击位置离网页窗口上边缘有多远;
touches:在触摸设备上确定用户用多少根手指触摸屏幕;
程序1 单击+计时
<!doctype html> <html lang="en"> <head> <title>Image Guess</title> <meta charset="utf-8"> <style type="text/css"> body{margin:20px;} img{margin:20px;} </style> <script language="JavaScript" type="text/JavaScript"> window.onload=init; //初始捕捉事件 function init(){ var images=document.getElementsByTagName("img"); for(var i=0;i<images.length;i++) images[i].onclick=showAnswer; } //处理单击事件 function showAnswer(e){//单击产生一个事件对象被传递 var image=e.target;//target指出触发事件的元素 var name=image.id; name=name+".jpg"; image.src=name; setTimeout(reblur, 2000, image); } //时间事件,2秒后变回模糊 function reblur(image) { var name = image.id; name = name + "blur.jpg"; image.src = name; } /* function init(){ var image=document.getElementById("zero"); image.onclick=showAnswer; } window.onload=init; function showAnswer(){ var image=document.getElementById("zero"); image.src="zero.jpg"; } */ //鼠标自动 /* window.onload = function() { var images = document.getElementsByTagName("img"); for (var i = 0; i < images.length; i++) { images[i].onmouseover = showAnswer; images[i].onmouseout = reblur; } }; function showAnswer(eventObj) { var image = eventObj.target; var name = image.id; name = name + ".jpg"; image.src = name; } function reblur(eventObj) { var image = eventObj.target; var name = image.id; name = name + "blur.jpg"; image.src = name; } */ </script> </head> <body> <img id="zero" src="zeroblur.jpg" /> <img id="one" src="oneblur.jpg" /> <img id="two" src="twoblur.jpg" /> <img id="three" src="threeblur.jpg" /> <img id="four" src="fourblur.jpg" /> <img id="five" src="fiveblur.jpg" /> </body> </html>
程序2 鼠标位置
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Pirates Booty</title> <script> window.onload = init; function init() { var map = document.getElementById("map"); map.onmousemove = showCoords; } function showCoords(eventObj) { var coords = document.getElementById("coords"); var x = eventObj.clientX;//获取位置 var y = eventObj.clientY; coords.innerHTML = "Map coordinates: " + x + ", " + y;//修改 } </script> </head> <body> <img id="map" src="map.jpg"> <p id="coords">Move mouse over map to find coordinates...</p> </body> </html>
3 事件群英谱
click:单击触发
load:加载完网页触发
unload:关闭或切换到其他网页触发
mousemove:在元素上移动鼠标触发
mouseover:鼠标移至元素上触发
mouseout:鼠标移开元素触发
keypress:按下任何键触发
resize:调整浏览器窗口大小触发
play:单击<video>元素播放按钮触发
pause:单击<video>元素暂停按钮触发
dragstart:用户拖曳网页元素时触发
drop:放下拖曳元素触发
touchstart:触摸设备,触摸并按住元素触发
touchend:停止触摸触发;