Event object in DOM
Introducing the Event object into DOM (the DOM browser is the standard browser)
(1) Pass the event through the event attribute of the HTML mark Object
In the DOM, the event object is passed to the function as a parameter when the event calls the function.
The event parameter is a fixed writing method of the system. It is all lowercase and cannot be quoted. It is the event object parameter.
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script type="text/javascript"> //在HTML中,如何通過(guò)事件來(lái)傳遞event對(duì)象參數(shù) function get(e){ //獲取單擊時(shí),距離窗口左邊和上邊的距離 alert(e.clientX+","+e.clientY); } </script> </head> <body style="margin:0px"> <img width="400" src="/upload/course/000/000/009/580af7f52278b486.jpg" onclick="get(event)" /> </body> </html>
(2) Use the event attribute of the element object to pass the event object
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script type="text/javascript"> window.onload = function(){ //獲取id=img1的圖片對(duì)象 var imgObj=document.getElementById("img1"); //增加onclick事件 imgObj.onclick=get; } //不能傳event參數(shù),但形參必須接收 //第一個(gè)形參,一定是event對(duì)象 function get(e){ //獲取單擊時(shí),距離窗口左邊和上邊的距離 alert(e.clientX+","+e.clientY); } </script> </head> <body style="margin:0px"> <img id="img1" width="400" src="/upload/course/000/000/009/580af7f52278b486.jpg" /> </body> </html>
##Event object properties in DOM
- type: the current event type
- clientX and clientY: distance from the left and top of the window
- pageX and pageY: distance from the left and top of the web page
- screenX and screenY: distance from the left and top of the screen
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script type="text/javascript"> function get(e) { //獲取單擊時(shí),相關(guān)坐標(biāo)信息 var str = "窗口左邊距離:"+e.clientX+",窗口頂邊距離:"+e.clientY; str += "\n網(wǎng)頁(yè)左邊距離:"+e.pageX+",網(wǎng)頁(yè)頂邊距離:"+e.pageY; str += "\n屏幕左邊距離:"+e.screenX+",屏幕頂邊距離:"+e.screenY; str += "\n事件類(lèi)型:"+e.type; window.alert(str); } </script> </head> <body style="margin:0px"> <img id="img1" width="400" src="/upload/course/000/000/009/580af7f52278b486.jpg" onclick="get(event)" /> </body> </html>