首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

js event 懂得与使用

2013-02-24 
js event 理解与使用event对象IE 中可以直接使用 event 对象,而 FF 中则不可以,解决方法之一如下:var theE

js event 理解与使用

event对象

IE 中可以直接使用 event 对象,而 FF 中则不可以,解决方法之一如下:

var theEvent = window.event || arguments.callee.caller.arguments[0];

第二种是将 event 作为参数来传递:

document.onclick=function xxx(e){var theEvent = window.event || e;}

?

srcElement 和 target

在 IE 中 srcElement 表示产生事件的源,比如是哪个按钮触发的 onclick 事件,FF 中则是 target。

var theEvent = window.event || arguments.callee.caller.arguments[0];

var theObj=theEvent.target || theEvent.srcElement;

例子:

document.onclick = function(e){

? ? ? ? ? ?var theEvent = window.event || e;

? ? ? ? ? ?var theObj=theEvent.target || theEvent.srcElement;

}

function clickAction(){

? ? ? ?var theEvent = window.event || arguments.callee.caller.arguments[0];

? ? ? ?var theObj=theEvent.target || theEvent.srcElement;

? ? ? ?// do something;

}

?

event.keyCode 和event.which

FF不支持window.event.keyCode,代替着是event.which

列子:

//在网页上面屏蔽tab键的代码

document.onkeydown = function (e){

? ? ? ? ? ? var theEvent = window.event || e;

? ? ? ? ? ? var code = theEvent.keyCode || theEvent.which;

? ? ? ? ? ? if(code == 9){

? ? ? ? ? ? ? return false;

? ? ? ? ? ? }

}

?

?

JavaScript 阻止冒泡

?

//阻止冒泡事件    function stopBubble(e) {        if (e && e.stopPropagation) {//非IE            e.stopPropagation();        }        else {//IE            window.event.cancelBubble = true;        }    } 

?

一个页面有两个click 事件,一个是div.onclick,另一个就是document.onclick,那么问题就出现了,在调用 div.onclick的时候,由于冒泡事件的存在,会自动的调用document.onclick,由于冒泡的顺序是从里向外的

(div->body->document->html)所以div.onclick事件就会被覆盖掉,也就不会执行了,解决的方案其实也是很简单的哦,就是在执行div.onclick的时候阻止冒泡事件就好了,那怎么阻止呢,就调用上面的函数就ok了!哈哈!?
ps:在介绍一下阻止浏览器默认行为的方法,大同小异,这里就不再赘述了。

?

Js代码  function stopDefault(e) {        //阻止默认浏览器动作(W3C)        if (e && e.preventDefault)            e.preventDefault();        //IE中阻止函数器默认动作的方式        else           window.event.returnValue = false;        return false;    }  

?

热点排行
Bad Request.