Event bindings fall into two categories:
One is the traditional event binding (inline model/script model), the previous chapter content;
One is the modern event binding (DOM2 level model); Modern event binding provides more powerful functions on the basis of traditional event binding;
A problem with a traditional event binding
//script model assigns a function to an event handler function; var box = document.getElementById (' box ');
Gets the element;
Box.onclick = function () {//Element click Trigger event;
Alert (' Lee ');
//Problem One: an event-handling function triggers two events;
Window.onload = function () {//The first set of programs;
Alert (' Lee ');
} window.onload = function () {//second group of programs;
Alert (' Mr.Lee ');
}//PS: When two sets of programs execute simultaneously, the latter one will cover the front one completely;
Causing the window.onload of the front to completely fail;
Solution: Window.onload = function () {//The first set of event handlers will be overwritten;
Alert (' Lee ');
} if (typeof window.onload = = ' function ') {//Judge whether there is window.onload before; var saved = null;
Create a Save device; saved = window.onload;
Save the previous window.onload;
} window.onload = function () {//next event to be executed; Saved () =window.onload = function if (saved) saved ();
Determine if there is an event before, and if so, first execute the previously saved event; Alert (' Mr.Lee ');
Execute the code for this event; }
/Question two: Event switcher Box.onclick = Boblue;
First execution of Toblue ();
function tored () {this.classname = ' red '; This.onclick = Toblue;
Perform roblue () for the third time, then switch back and forth;
function Toblue () {this.classname = ' blue '; This.onclick = tored;
Second execution tored ();
}//This switch when expanding, there will be some problems: 1. If you add an executive function, it will be overwritten; Box.onclick = Toalert;
The added function; Box.onclick = Toblue;
The toalert was covered;
2. If the coverage problem is addressed, it must include simultaneous implementation;
Box.onclick = function () {//included, but less readable; Toalert ();
The first time will not be covered, but the second time is covered; Toblue.call (this);
This must also be passed to the switch; }
//Comprehensive three questions: overlay problem/readability problem/this transfer as the problem;//We create a custom event handler function;
function Addevent (OBJ,TYPE,FN) {//replaces traditional event-handling functions; var saved = null;
Save the event handler function for each trigger;
if (typeof obj[' on ' +type] = = ' function ') {//To judge whether there is an event; Saved = obj[' on ' +type];
If there is, save it;
} obj[' on ' +type] = function () {//Then execute; if (saved) saved ();
implementation of the previous; Fn.call (this);
Execute the function and pass this in; } addevent (window, ' Load ', function () {alert (' Lee ');
can be implemented;
}); addevent (window. ' Load ', function () {alert (' Mr.Lee ');
can be implemented;
//////register with a custom event function on the switch to see the effect: addevent (window, ' Load ', function () {var box = document.getElementById (' box ');
addevent (box, ' click ', Toblue);
});
function tored () {this.classname = ' red ';
Addevent (This, ' click ', Toblue);
function Toblue () {this.classname = ' blue ';
Addevent (This, ' click ', tored);
The
two-way event handler
//DOM2 level event defines two methods for adding and removing handlers for events: AddEventListener () and RemoveEventListener () ;
Both methods are included in all DOM nodes, and they all receive 3 parameters: the event name/function/bubble or the captured Boolean value (true means capture, false indicates bubbling);
Window.addeventlistener (' Load ', function () {alert (' Lee ');
},false);
Window.addeventlistener (' Load ', function () {alert (' Mr.Lee ');
},false);
PS:W3C Event Binding Benefits: 1. No customization required; 2. can mask the same function; 3. You can set bubbles and captures; Window.addeventlistener (' Load ', init,false);
For the first time executed; Window.addeventlistener (' Load ', init,false);
Was shielded for the second time;
function init () {alert (' Lee ');
///Event switcher Window.addeventlistener (' Load ', function () {var box = document.getElementById (' box ');
Box.addeventlistener (' click ', function () {///will not be overwritten/mistakenly deleted;
Alert (' Lee ');
},false); Box.addeventlistener (' click ', Toblue,false);
introduction of switching;
},false);
function tored () {this.classname = ' red '; This.removeeventlistener (' click ', Tored,false);
Remove the event handler function; This.addeventlistener (' click ', Toblue,false);
Add event handler functions that need to be switched;
function Toblue () {this.classname = ' blue ';
This.removeeventlistener (' click ', Toblue,false); THis.addeventlistener (' click ', Tored,false);
//Set bubble and capture phase Document.addeventlistener (' click ', function () {alert (' document '); },true);
Set to capture;
Document.addeventlistener (' click ', function () {alert (' Lee '); },false); set to bubbling;
Three IE event handler functions
//IE has implemented two methods similar to DOM: Attachevent () and detachevent ();
The two methods receive the same parameters: the event name and the function;
When using these two sets of functions, the difference://1.IE does not support capture, only support bubbling;
2.IE Add event cannot mask duplicate function;
This in 3.IE points to window rather than to a DOM object;
4. In traditional events, IE is not acceptable to the event object, but the use of attachevent () but can;
Window.attachevent (' onload ', function () {var box = document.getElementById (' box ');
Box.attachevent (' onclick ', toblue);
});
function tored () {var that = window.event.srcElement;
That.classname = ' red ';
That.detachevent (' onclick ', tored);
That.attachevent (' onclick ', toblue);
function Toblue () {var that = window.event.srcElement;
That.classname = ' Blue ';
That.detachevent (' onclick ', toblue);
That.attachevent (' onclick ', tored);
The capture is not supported by//Ps:ie;
IE can not be shielded;
IE cannot pass this, can call the past;
On traditional bindings, IE is not able to accept the event object as a attachevent, but if it is used (); Box.onclick = function (evt) {alert (EVT);
Undefined } box.attachevent (' onclick ', function (evt) {alert (EVT);
Object alert (Evt.type);
Click
});
Event switcher functions compatible with IE and the consortium; function Addevent (oBJ,TYPE,FN) {//Add event handler compatible;
if (Obj.addeventlistener) {Obj.addeventlistener (TYPE,FN);
}else if (obj.attachevent) {obj.attachevent (' on ' +type,fn);
} function Removeevent (OBJ,TYPE,FN) {//Remove event handler compatibility;
if (Obj.removeeventlistener) {Obj.removeeventlistener (TYPE,FN);
}esle if (obj.detachevent) {obj.detachevent (' on ' +type,fn);
} function Gettarget (evt) {//Get event target;
if (evt.target) {return evt.target;
}else if (window.event.srcEleemnt) {return window.event.srcElement; }
}
Four event objects complement
1.relatedTarget
//This property can get a DOM object from where and from where to move in the mouseover and mouseout events;
Box.onmouseover = function (evt) { //mouse move into box;
alert (evt.relatedtarget); Gets the element before the box is moved into
;
Box.onmouseout = function (evt) { //mouse move out of box;
alert (evt.relatedtarget); Gets the element that came after the box was moved out;
IE provides two sets of properties corresponding to them: Fromelement and toelement;
Compatible functions function
Getearget (evt) {
var e = evt | | window.event; Get the event object;
if (e.srcelement) { //If srcelement is supported, IE is indicated;
if (E.type = = ' MouseOver ') { //If it is over event;
return e.fromeelement; Use from;
} else if (E.type = = ' Mouseout ') { //if it is out;
return e.toelement; Use to;
}
else if (e.relatedtarget) { //If Relatedtarget is supported, the consortium is represented;
Return E.relatedtarget
}
}
2. Prevent the default behavior of events
//The default behavior of a hyperlink is clicked and then jumps to the specified page;//So blocking the default behavior can mask the jump of this operation, and implement custom actions;//Cancel event default behavior there is an irregular approach,
is to return false;
Link.onclick = function () {alert (' Lee '); return false;
Returns false directly, will not jump;
}//PS: Although return false, this functionality can be implemented, but there are vulnerabilities;
First: The code must be written to the last, so that after the middle code executes, it is possible to perform a return false;
Second: return false to the top then the custom operation will fail;
Solution: Block the default behavior at the front, and execute code later;
function Predef (evt) {//Cross-browser compatible blocking default behavior; var e = evt | |
window.event; if (E.preventdefault) {e.preventdefault ();
The consortium to prevent default behavior; }else{E.returnvalue = false;
IE, block default behavior; }
}
3. Context Menu Event ContextMenu
//When we right-click the page, Windows will automatically appear with the menu;
Then we can use the ContextMenu event to modify the menu we specify, but only if the default behavior of right-clicking is canceled;
addevent (window, ' Load ', function () {
var text = Docuemnt.getelementbyid (' text ');
Addevent (text, ' ContextMenu ', function (evt) { //Add right-click menu event handler;
var e = evt | | window.event;
Predef (e); Block default behavior functions;
var menu = document.getElementById (' menu '); Locate the custom menu object;
Menu.style.left = e.clientx+ ' px '; Determines the location of the custom menu on the screen;
Menu.style.top = e.clientx+ ' px ';
menu.style.visibility = ' visible '; The property of the custom menu is set to visible;
Addevent (document, ' click ', Function () { //Add a click event handler to the document;
Docuemnt.getelementbyid (' MyMenu '). style.visibility = ' hidden '; Hide the custom menu;};});
4. Pre-Uninstall Event Beforeunload
This event can help you to give a hint when you leave this page. Leave "or" return "operation;
addevent (window. ' Beforeunload ', function (evt) {
var evt = Event | | window.event;
var message = ' Do you want to leave this page? '
Evt.returnvalue = message;
return message;
});
5. Mouse wheel (mousewheel) and Dommousescroll
Used to get the distance between the mouse and the scroll wheel;
Addevent (docuemnt, ' MouseWheel ', function (evt) { //non-Firefox;
Alert (GETWD (EVT));
});
Addevent (docuemnt, ' Dommousescroll ', function (evt) { //Firefox;
Alert (GETWD (EVT));
});
function Getwd (evt) {
var e = evt | | window.event;
The IF (E.wheeldelta) { //MouseWheel event's scrolling value is saved in the Wheeldelta;
return e.wheeldelta;
} else if (e.detail) { //Dommousescroll event's scrolling value is saved in detail;
return-evt.detail*30; Maintain a unified calculation;
}