鼠标事件event和坐标

鼠标事件(e=e||window.event)

event.clientX、event.clientY

鼠标相对于浏览器窗口可视区域的X,Y坐标(窗口坐标),可视区域不包括工具栏和滚动条。IE事件和标准事件都定义了这2个属性

event.pageX、event.pageY

类似于event.clientX、event.clientY,但它们使用的是文档坐标而非窗口坐标。这2个属性不是标准属性,但得到了广泛支持。IE事件中没有这2个属性。

event.offsetX、event.offsetY

鼠标相对于事件源元素(srcElement)的X,Y坐标,只有IE事件有这2个属性,标准事件没有对应的属性。

event.screenX、event.screenY

鼠标相对于用户显示器屏幕左上角的X,Y坐标。标准事件和IE事件都定义了这2个属性

知识点1:确定鼠标按钮(event.button

实例

<html>
<head>
<script type="text/javascript">
function whichButton(event)
{
var btnNum = event.button;
if (btnNum==2)
  {
  alert("您点击了鼠标右键!")
  }
else if(btnNum==0)
  {
  alert("您点击了鼠标左键!")
  }
else if(btnNum==1)
  {
  alert("您点击了鼠标中键!");
  }
else
  {
  alert("您点击了" + btnNum+ "号键,我不能确定它的名称。");
  }
}
</script>
</head>

<body onmousedown="whichButton(event)">
<p>请在文档中点击鼠标。一个消息框会提示出您点击了哪个鼠标按键。</p>
</body>

</html>

知识点2:鼠标相对屏幕的距离(x=event.screenX  /  y=event.screenY ) 

实例

<html>
<head>

<script type="text/javascript">
function coordinates(event)
{
x=event.screenX
y=event.screenY
alert("X=" + x + " Y=" + y)
}

</script>
</head>
<body onmousedown="coordinates(event)">

<p>
在文档中点击某个位置。消息框会提示出指针相对于屏幕的 x 和 y 坐标。
</p>

</body>
</html>

知识点3:鼠标相对于浏览器窗口的坐标( x=event.clientX / y=event.clientY 

<html>
<head>
<script type="text/javascript">
function show_coords(event)
{
x=event.clientX
y=event.clientY
alert("X 坐标: " + x + ", Y 坐标: " + y)
}
</script>
</head>

<body onmousedown="show_coords(event)">

<p>请在文档中点击。一个消息框会提示出鼠标指针的 x 和 y 坐标。</p>

</body>
</html>

知识点4:获取键盘的按键的 unicode(event.keyCode)

<html>
<head>
<script type="text/javascript">
function whichButton(event)
{
alert(event.keyCode)
}

</script>
</head>

<body onkeyup="whichButton(event)">
<p><b>注释:</b>在测试这个例子时,要确保右侧的框架获得了焦点。</p>
<p>在键盘上按一个键。消息框会提示出该按键的 unicode。</p>
</body>

</html>
原文地址:https://www.cnblogs.com/qdlhj/p/10044793.html