好像各大类库中jQuery是最后支持这两东东的,关于它们的优势可以参考reglib类库作者的一篇博文《Goodbye mouseover, hello mouseenter》。我们可以在IE观察下它的效果。
注意,我们在红色与蓝色之间移动,并没有触发outer元素的mouseenter事件。无错,它们与mouseover,mouseout最大的区别是它们不会冒泡。
下面试图用mouseover与mouseout模拟mouseenter与mouseleave。
function addEvent(el, type, handler, capture) {
if (typeof el.addEventListener != 'undefined') {
if (type === 'mouseenter') {
el.addEventListener('mouseover', withinElement(handler), capture);
} else if (type === 'mouseleave') {
el.addEventListener('mouseout', withinElement(handler), capture);
} else {
el.addEventListener(type, handler, capture);
}
} else if (typeof el.attachEvent != 'undefined') {
el.attachEvent('on' + type, handler);
} else {
el['on' + type] = handler;
}
}
function withinElement(handler) {
return function (e) {
var parent = e.relatedTarget;
while ( parent && parent != this ) {
try { parent = parent.parentNode; }
catch(e) { break; }
}
if ( parent != this )
handler.call(this, e);
};
};
var $ = function(id){
return document.getElementById(id);
}
window.onload = function(){
function myFn(e){
e = e || window.event;
var target = e.target ? e.target : e.srcElement;
if(target.nodeType === 3){
target = target.parentNode;
}
$('memo').innerHTML = e.type + ': ' + target.id;
};
addEvent($("inner"),"mouseenter",myFn,false);
addEvent($("inner"),"mouseleave",myFn,false);
addEvent($("outer"),"mouseenter",myFn,false);
}
看看jQuery的实现,它用了一个冒牌事件对象,因此我们可以在FF中用e.type能打印出mouseenter,除此与上面没多大改善。