Home >Web Front-end >JS Tutorial >Add implementation code for mouseenter and mouseleave events for non-IE browsers_javascript skills

Add implementation code for mouseenter and mouseleave events for non-IE browsers_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:05:351125browse

First understand a few event object attributes

target refers to the event source object. Click on an element at the innermost level of the nested element, and that element is the target. IE6/7/8 corresponds to srcElement.

currentTarget refers to the element itself where the event handler is added. For example, in el.addEventListener, el is the currentTarget. IE6/7/8 does not have a corresponding attribute. You can use this in the handler instead, such as evt.currentTarget = this.

relativeTarget refers to event-related elements, generally used in mouseover and mouseout events. The corresponding ones in IE6/7/8 are fromElement and toElement.
mouseenter, mouseleave are still supported in IE9, see also Greg Reimer’s blog post Goodbye mouseover, hello mouseenter.
The difference between mouseenter and mouseover is that mouseenter will not trigger when moving inside the element. As follows

Copy the code The code is as follows:


< html>


mouseerter and mouseover Difference (tested under IE)




1, the mouse moves inside div[id=parent1] The mouseover event will also be triggered



Child11

Child12





2, the mouseenter event will not be triggered when the mouse moves inside div[id=parent2]




Child22







Got it After the meaning of these three attributes, it is simple to implement:
Copy the code The code is as follows:

E = function(){
function elContains(a, b){
try{
return a.contains ? a != b && a.contains(b) : !!(a.compareDocumentPosition (b) & 16);
}catch(e){}
}
function addEvt(el, type, fn){
function fun(e){
var a = e .currentTarget, b = e.relatedTarget;
if(!elContains(a, b) && a!=b){
fn.call(e.currentTarget,e);
}
}
if(el.addEventListener){
if(type=='mouseenter'){
el.addEventListener('mouseover', fun, false);
}else if(type==' mouseleave'){
el.addEventListener('mouseout', fun, false);
}else{
el.addEventListener(type, fn, false);
}
}else{
el.attachEvent('on' type, fn);
}
}
return {addEvt:addEvt};
}();

Test Code:

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn