如果您使用纯 javascript 进行自己的事件处理,那么您可能已经有一个用于设置事件处理程序的跨浏览器例程。您可以将抽象放在该函数中。这是我使用的一个模仿 jQuery 功能的函数(如果事件处理程序返回false
,则两者都stopPropagation()
被preventDefault()
触发。您显然可以修改它,但是您希望它的行为:
// refined add event cross browser
function addEvent(elem, event, fn) {
// allow the passing of an element id string instead of the DOM elem
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// normalize the target of the event
window.event.target = window.event.srcElement;
// make sure the event is passed to the fn also so that works the same too
// set the this pointer same as addEventListener when fn is called
var ret = fn.call(elem, window.event);
// support an optional return false to be cancel propagation and prevent default handling
// like jQuery does
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
或者,您可以像这样创建一个实用函数:
function stopPropagation(e) {
if(e.stopPropagation) {
e.stopPropagation();
} else {
e.returnValue = false;
}
}
并且只需调用该函数而不是对每个函数中的事件进行操作。