关于鼠标、键盘的几个例子

  1 1. 鼠标的哪个按键被点击?
  2 <html>
  3 <head>
  4 <script type="text/javascript">
  5 function whichButton(event)
  6 {
  7 if (event.button==2)
  8 {
  9 alert("你点击了鼠标右键!")
 10 }
 11 else
 12 {
 13 alert("你点击了鼠标左键!")
 14 }
 15 }
 16 </script>
 17 </head>
 18 
 19 <body onmousedown="whichButton(event)">
 20 <p>请单击你鼠标的左键或右键试试</p>
 21 </body>
 22 </html>
 23 
 24 2. 当前鼠标的光标坐标是多少?
 25 <html>
 26 <head>
 27 <script type="text/javascript">
 28 function show_coords(event)
 29 {
 30 x=event.clientX
 31 y=event.clientY
 32 alert("X 坐标: " + x + ", Y 坐标: " + y)
 33 }
 34 </script>
 35 </head>
 36 
 37 <body onmousedown="show_coords(event)">
 38 
 39 <p>在此文档中按下你鼠标的左键看看!</p>
 40 
 41 </body>
 42 </html>
 43 
 44 
 45 3. 被按下键的unicode码是多少?
 46 <html>
 47 <head>
 48 <script type="text/javascript">
 49 function whichButton(event)
 50 {
 51 alert(event.keyCode)
 52 }
 53 
 54 </script>
 55 </head>
 56 
 57 <body onkeyup="whichButton(event)">
 58 <p>在此文档中按下你键盘上的某个键看看</p>
 59 </body>
 60 </html>
 61 
 62 4. 当前鼠标的光标相对于屏幕的坐标是多少?
 63 <html>
 64 <head>
 65 
 66 <script type="text/javascript">
 67 function coordinates(event)
 68 {
 69 x=event.screenX
 70 y=event.screenY
 71 alert("X=" + x + " Y=" + y)
 72 }
 73 
 74 </script>
 75 </head>
 76 <body onmousedown="coordinates(event)">
 77 
 78 <p>
 79 点击你鼠标的左键
 80 </p>
 81 
 82 </body>
 83 </html>
 84 
 85 5. 当前鼠标的光标坐标是多少?
 86 <html>
 87 <head>
 88 
 89 <script type="text/javascript">
 90 function coordinates(event)
 91 {
 92 x=event.x
 93 y=event.y
 94 alert("X=" + x + " Y=" + y)
 95 }
 96 
 97 </script>
 98 </head>
 99 <body onmousedown="coordinates(event)">
100 
101 <p>
102 点击你鼠标的左键
103 </p>
104 
105 </body>
106 </html>
107 
108 6。shift键是否按下?
109 <html>
110 <head>
111 <script type="text/javascript">
112 function isKeyPressed(event)
113 {
114   if (event.shiftKey==1)
115     {
116     alert("shit键按下了!")
117     }
118   else
119     {
120     alert("shit键没有按下!")
121     }
122   }
123 </script>
124 </head>
125 
126 <body onmousedown="isKeyPressed(event)">
127 
128 <p>按下shit键,点击你鼠标的左键</p>
129 
130 </body>
131 </html>
132 
133 7. 当前被点击的是哪一个元素?
134 <html>
135 <head>
136 <script type="text/javascript">
137 function whichElement(e)
138 {
139 var targ
140 if (!e) var e = window.event
141 if (e.target) targ = e.target
142 else if (e.srcElement) targ = e.srcElement
143 if (targ.nodeType == 3) // defeat Safari bug
144    targ = targ.parentNode
145 var tname
146 tname=targ.tagName
147 alert("你点击了 " + tname + "元素")
148 }
149 </script>
150 </head>
151 
152 <body onmousedown="whichElement(event)">
153 <p>在这里点击看看,这里是p</p>
154 <br /><br />
155 <h3>或者点击这里也可以呀,这里是h3</h3>
156 <p>你想点我吗??</p>
157 <img border="0" src="../myCode/btn.gif" width="100" height="26" alt="pic">
158 </body>
159 
160 </html>
原文地址:https://www.cnblogs.com/ITzhangyunpeng/p/9365900.html