本文實例講述了js鼠標按鍵事件和鍵盤按鍵事件用法。分享給大家供大家參考,具體如下:
keydown,keyup,keypress:屬于你的鍵盤按鍵
mousedown,mouseup:屬于你的鼠標按鍵
當按鈕被按下時,發生 keydown 事件,
keyup是在用戶將按鍵抬起的時候才會觸發的,
完整的 key press 過程分為兩個部分:1. 按鍵被按下;2. 按鍵被松開。
當用戶在這個元素上按下鼠標鍵的時候,發生mousedown
當用戶在這個元素上松開鼠標鍵的時候,發生mouseup
例子
1. 鼠標的哪個按鍵被點擊
<html><head><script type="text/javascript">function whichButton(event){if (event.button==2){alert("你點擊了鼠標右鍵!")}else{alert("你點擊了鼠標左鍵!")}}</script></head><body onmousedown="whichButton(event)"><p>請單擊你鼠標的左鍵或右鍵試試</p></body></html>
2. 當前鼠標的光標坐標是多少
<html><head><script type="text/javascript">function show_coords(event){x=event.clientXy=event.clientYalert("X 坐標: " + x + ", Y 坐標: " + y)}</script></head><body onmousedown="show_coords(event)"><p>在此文檔中按下你鼠標的左鍵看看!</p></body></html>
3. 被按下鍵的unicode碼是多少
<html><head><script type="text/javascript">function whichButton(event){alert(event.keyCode)}</script></head><body onkeyup="whichButton(event)"><p>在此文檔中按下你鍵盤上的某個鍵看看</p></body></html>
4. 當前鼠標的光標相對于屏幕的坐標是多少
<html><head><script type="text/javascript">function coordinates(event){x=event.screenXy=event.screenYalert("X=" + x + " Y=" + y)}</script></head><body onmousedown="coordinates(event)"><p>點擊你鼠標的左鍵</p></body></html>
5. 當前鼠標的光標坐標是多少
<html><head><script type="text/javascript">function coordinates(event){x=event.xy=event.yalert("X=" + x + " Y=" + y)}</script></head><body onmousedown="coordinates(event)"><p>點擊你鼠標的左鍵</p></body></html>
6. shift鍵是否按下
<html><head><script type="text/javascript">function isKeyPressed(event){if (event.shiftKey==1){alert("shit鍵按下了!")}else{alert("shit鍵沒有按下!")}}</script></head><body onmousedown="isKeyPressed(event)"><p>按下shit鍵,點擊你鼠標的左鍵</p></body></html>
7. 當前被點擊的是哪一個元素
<html><head><script type="text/javascript">function whichElement(e){var targif (!e) var e = window.eventif (e.target) targ = e.targetelse if (e.srcElement) targ = e.srcElementif (targ.nodeType == 3) // defeat Safari bugtarg = targ.parentNodevar tnametname=targ.tagNamealert("你點擊了 " + tname + "元素")}</script></head><body onmousedown="whichElement(event)"><p>在這里點擊看看,這里是p</p><h3>或者點擊這里也可以呀,這里是h3</h3><p>你想點我嗎??</p><img border="0" src="../myCode/btn.gif" width="100" height="26" alt="pic"></body></html>
PS:這里再為大家提供一個關于JS事件的在線工具,歸納總結了JS常用的事件類型與函數功能:
javascript事件與功能說明大全:
http://tools.VeVB.COm/table/javascript_event
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript窗口操作與技巧匯總》、《JavaScript中json操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答