Cross-browser MouseEnter mouseleave and comparedocumentposition usage instructions _javascript tips

Source: Internet
Author: User

Written for so long JS application I actually did not know these two events so went to Google to search for some. Only to discover that these two events are so excellent and easy to use ...  But the search process found that many people do not seem to understand the two events and MouseOver mouseout real difference and use. and see the Cross-browser solution that some of the friends in Google are implementing. I think it seems a little cumbersome ... So there's the urge to write a blog and say this thing thoroughly ... All right, let's get to the point.

The biggest difference between the two events for MouseOver and MouseEnter is that mouseenter are not bubbling events. How do you understand that?

<div id== "Parent" >
<div id= "Child" ></div>
</div>

For mouseover time occurs when the mouse moves from other elements to the child node but this event bubbles so that parent also departs MouseOver

If we register mouseover listening to parent. What might be the problem? Moving from parent to child same mouseover of parent sometimes we don't want this to happen. At this point, if the registered listener is MouseEnter, no matter when the mouse moves from any element to the child, only the child element occurs MouseEnter event and its ancestor node does not trigger this event because of bubbling ... This allows us to completely give up the solution that we used to have in order to implement the same logic, and to prevent mouseover bubbling or to judge the source object of the event or to Judge Srcelement/relatedtarget as troublesome.

The same is true for Mouseout and MouseLeave. Mouseout also bubbles to parent when the mouse moves out of the child, triggering the mouseout two mouseleave of parent as well.

It would be much better to know the difference between the remaining things. We all MouseEnter MouseLeave to meet this kind of demand. The question is, what about this thing that only IE supports?

We can only use mouseover and mouseout to simulate it, but if our simulations are too complicated, that's not going to make sense ... At this point, we can use the XML method comparedocumentposition to solve this problem completely

I encapsulate a method in my class library that is designed to determine whether a node's position is in the child node of another node ...

IE can use Parentnode.contains (Childnode) to judge that there is nothing to say childnode in the ParentNode DOM tree is True

and contains method ie exclusive so we are with the help!! (Node.comparedocumentposition (Node2) &16) to achieve the same effect.

Then we'll talk about the Comparedocumentposition method otherwise you see the above &16 must be very confused ...

The Comparedocumentposition method is implemented in the node object in non IE browsers, so

The role of Node.comparedocumentposition (Node2) is to compare the location relationship between node nodes and Node2 nodes.

His return value is a number value ...

The following values are generally useful to us

1.20 (2-in-010100)

2.10 (2-in-001010)

3.4 (2-in-000100)

4.2 (2-in-000010)

5.0 (2-in-000000)

6.2 Number of 100*** ...

So how did these 20 10 4 2 0 come from? We went on to look down ...

Try this 2 algorithm is specifically used to explain the relationship between the two nodes

This 6-bit 2-digit number is fundamental.

The 6th digit represents two nodes whether one is in the DOM tree and one is not in this case for the entire DOM tree. That is, if two are not present or two are all in 0 or 1

The 5th bit represents whether node is a node2 parent node if it is 1 or 0

The 4th bit represents whether node is a node2 child node if it is 1 or 0

The 3rd bit indicates whether node is in front of the Node2 if it is 1 otherwise 0 (note: If node is Node2 's parent section node is also considered to be in front of Node2)

The 2nd bit indicates whether node is behind the Node2 if it is 1 or 0 (Note If node is a Node2 node, node is also considered to be behind Node2)

Finally, if 2 3 4 5 6 digits are 0 or 000000, then two nodes are either in the DOM tree or not at the same time. and two nodes have nothing to do with it, then only one possibility is that two nodes are the same node ... which is node==node2.

So what is the result of the Node.comparedocumentposition (node2) &16 bit operation? Of the above several possible combinations only 010100 &010000 and 110*** &16 result is 010000 that returns 16 other cases return 0 and then use!! Number implicitly transformed into a Boolean type we can tell if node is the parent of node2 ...

So we can also use Node2.comparedocumentposition (node) && 8来 to determine if Node2 is the same as the node's subnodes.

Or we can also directly node.comparedocumentposition (Node2) ==20 to make judgments so can also be omitted!! Make a transition. is also possible.

When you get here, you must have found out what this thing is. Clearly is the use of flag identity enumeration in C # ...

File.attributes enumerations in C # may also have n multiple attributes such as a file can be read-only while it can be hidden, or it can be shared at the same time. Wait a minute

So how do you use an enumeration value to determine what attributes a file has at the same time without conflict? The answer to Comparedocumentposition is the same ...

I use JS to implement a similar logic to manage the flag identity class to illustrate the problem code as follows

//Flag class
    function Flag (sflags) {
        this._flags = {};
        this._status = 0;
        sflags && this.initflags (sflags);
   }
    flag.prototype = {
        constructor:flag,
        initflags:function (sflags) {//sflags State 1, State 2, State 3 ... Initialize the original Identity collection ...
            sflags = Sflags.split (', ');
            for (var i = 0, Len = Sflags.length; i < Len; i++) This._flags[sflags[i] = 1 << i;

This initializes the value of the identity if it has n states at the same time, the value of each state must be 000001 000010 000100 001000 010000 100000
},
Setstatus:function (sflags) {//sflags State 1, State 3 ... Set Current state
Sflags = Sflags.split (', ');

this._status=0;
for (var i = 0, len = sflags.length i < len; i++) {
This._check[sflags[i]];
This._status |= This._flags[sflags[i]];
}
},
Addstatus:function (sflags) {//sflags State 1, State 3 ... Check that the current status indicates whether there is a status of 1 and state 3 if not then add
Sflags = Sflags.split (', ');
for (var i = 0, len = sflags.length i < len; i++) {
This._check (Sflags[i]);
if (This.hasstatus (Sflags[i])) continue;//To determine if there is already this state if there is a skip.
                this._status |= This._flags[sflags[i]];

               //Current status value   With the allowed identity value to do | Operations   Add status
           }
        },
        removestatus:function (sflags) {
            sflags = Sflags.split (', ');
            for (var i = 0, len = sflags.length i < len; i+ +) {
                This._check ( Sflags[i]);
                if (! This.hasstatus (Sflags[i]) continue;
                this._status ^= This._flags[sflags[i]];

The current state value and the state value to be removed do the ^ operation-delete state
}
},
Clear:function () {
This._status = 0;
},
Hasstatus:function (sflags) {//sflags State 1, State 3 ... State N. Check that the current status ID has both State 1 and State 3 and State n
Sflags = Sflags.split (', ');
for (var i = 0, len = sflags.length i < len; i++) {
This._check (Sflags[i]);
if ((This._status & This._flags[sflags[i]])!= This._flags[sflags[i]) return false;

Current state value and input state do & operations returns False if the return value does not equal the identity value of the change state.

For example 010101 & 010000 return 010000 indicates that the current identity value has 010000 this state.

}
return true;
},
_check:function (Sflag) {
if (!sflag in this._flags) throw new Error ("The current flag does not exist" + Sflag + "identity");

Checks whether the current input status string is a valid value.
}
}

Usage:

VAR filestatus=new flag (' Readonly,hidden,otherstatus ');

Filestatus.setstatus (' Readonly,hidden ');

Alert (filestatus.hasstatus (' readOnly '))//true;

Alert (Filestatus.hasstatus (' hidden '))//true;

Alert (filestatus.hasstatus (' Otherstatus '))//false;

Finally, let's get back to the point where we use comparedocumentposition to simulate MouseEnter MouseLeave

DOM Structure:

<div id= "dd" style= "Background-color: #369; width:50%;height:50%;p osition:absolute;left:25%;top:25%;" >
<div style= "Background-color: #ff0; width:50%;height:50%;p osition:relative;left:25%;top:25%" >
<div style= "Background-color: #789; width:50%;height:50%;p osition:relative;left:25%;top:25%" >
<div style= "Background-color: #123; width:50%;height:50%;p osition:relative;left:25%;top:25%" >
<div style= "Background-color: #456; width:50%;height:50%;p osition:relative;left:25%;top:25%" >
</div>
</div>
</div>
</div>
</div>

JS script:

var dd = document.getElementById (' dd ')

if (! + ' \v1 ') {//ie
Dd.onmouseenter = function () {alert (1);};
Dd.onmouseleave = function () {alert (2);};
}
else {//others
Dd.onmouseover = function (e) {
var t = E.relatedtarget;
var t2 = E.target;
this = = T2 && t &&! (T.comparedocumentposition (this) & 8) && alert (1);
};
Dd.onmouseout = function (e) {
var t = E.relatedtarget;
var t2 = E.target;
this = = T2 && t &&! (T.comparedocumentposition (this) & 8) && alert (2);
};
}

Done!!!!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.