日期:2014-05-16  浏览次数:20299 次

详尽解析JavaScript中window.event对象

详尽解析JavaScript中window.event对象,阅读详尽解析JavaScript中window.event对象,描述event代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等。event对象只在事件发生的过程中才有效。event的某些属性只对特定的事件有意义。比如:

描述
event代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等。
event对象只在事件发生的过程中才有效。
event的某些属性只对特定的事件有意义。比如,fromElement 和 toElement 属性只对 onmouseover 和 onmouseout 事件有意义。
例子下面的例子检查鼠标是否在链接上单击,并且,如果shift键被按下,就取消链接的跳转。
?
<HTML>
<HEAD><TITLE>Cancels Links</TITLE>
<SCRIPT LANGUAGE="JScript">
function cancelLink() {
if (window.event.srcElement.tagName == "A" && window.event.shiftKey)
window.event.returnValue = false;
}
</SCRIPT>
<BODY onclick="cancelLink()">下面的例子在状态栏上显示鼠标的当前位置。
<BODY onmousemove="window.status = 'X=' + window.event.x + ' Y=' + window.event.y">属性:
altKey, button, cancelBubble, clientX, clientY, ctrlKey, fromElement, keyCode, offsetX, offsetY, propertyName, returnValue, screenX, screenY, shiftKey, srcElement, srcFilter, toElement, type, x, y
1.altKey
描述:
检查alt键的状态。
语法:
event.altKey
可能的值:
当alt键按下时,值为 TRUE ,否则为 FALSE 。只读。
2.button
描述:
检查按下的鼠标键。
语法:
event.button
可能的值:
0 没按键
1 按左键
2 按右键
3 按左右键
4 按中间键
5 按左键和中间键
6 按右键和中间键
7 按所有的键
这个属性仅用于onmousedown, onmouseup, 和 onmousemove 事件。对其他事件,不管鼠标状态如何,都返回 0(比如onclick)。
3.cancelBubble
描述:
检测是否接受上层元素的事件的控制。
语法:
event.cancelBubble[ = cancelBubble]
可能的值:
这是一个可读写的布尔值:
TRUE 不被上层原素的事件控制。
FALSE 允许被上层元素的事件控制。这是默认值。
例子:
下面的代码片断演示了当在图片上点击(onclick)时,如果同时shift键也被按下,就取消上层元素(body)上的事件onclick所引发的showSrc()函数。
<SCRIPT LANGUAGE="JScript">
function checkCancel() {
if (window.event.shiftKey)
window.event.cancelBubble = true;
}
function showSrc() {
if (window.event.srcElement.tagName == "IMG")
alert(window.event.srcElement.src);