JavaScript event binding and depth
- 2020-05-27 04:27:11
- OfStack
There are two types of event binding:
One is traditional event binding (inline model/script model); The content of the previous chapter;
One is modern event binding (DOM2-level model); Modern event binding provides more powerful functions on the basis of traditional event binding.
The problem of traditional event binding
// The script model will 1 Three functions are assigned to 1 Event handlers ;
var box = document.getElementById('box'); // Access to elements ;
box.onclick = function(){ // Element click to trigger the event ;
alert('Lee');
}
// The problem 1:1 Two event handlers fire two events ;
window.onload = function(){ // The first 1 Set of programs ;
alert('Lee');
}
window.onload = function(){ // The first 2 Set of programs ;
alert('Mr.Lee');
}
// PS: When two sets of programs are executed simultaneously , behind 1 One will turn the front 1 Total coverage ;
// Leading up to window.onload Completely failed ;
// The solution :
window.onload = function(){ // The first 1 Group event handler , Will be overwritten ;
alert('Lee');
}
if(typeof window.onload == 'function'){ // Determine if there was before window.onload;
var saved = null; // create 1 A conservator ;
saved = window.onload; // The previous window.onload Save up ;
}
window.onload = function(){ // Under the 1 An event to be executed ;
// saved()=window.onload = function
if(saved)saved(); // Determine if there were any previous events , If so, execute the previously saved event ;
alert('Mr.Lee'); // Execute the code for this event ;
}
// The problem 2: Event switcher
box.onclick = boBlue; // The first 1 Time to perform toBlue();
function toRed(){
this.className = 'red';
this.onclick = toBlue; // The first 3 Time to perform roBlue(), And then back and forth ;
}
function toBlue(){
this.className = 'blue';
this.onclick = toRed; // The first 2 Time to perform toRed();
}
// The switcher is extended , There will be a 1 Some problems :
1. If you add 1 Three executive functions , So it's going to be overwritten ;
box.onclick = toAlert; // The added function ;
box.onclick = toBlue; // toAlert Be covered ;
2. If you solve the coverage problem , Must include simultaneous execution ;
box.onclick = function(){ // included , But it's less readable ;
toAlert(); // The first 1 The second will not be overwritten , But the first 2 The second is covered again ;
toBlue.call(this); // Also must put this Pass it to the switcher ;
}
// To sum up 3 A question : Covering problem / Readability problem /this Transfer title ;
// We create 1 Two custom event handlers ;
function addEvent(obj,type,fn){ // Replace traditional event handlers ;
var saved = null; // Save the event handler for each event that is fired ;
if(typeof obj['on'+type] == 'function'){// Determine if there is an event ;
saved = obj['on'+type]; // If you have , Save up ;
}
obj['on'+type] = function(){ // Then perform ;
if(saved)saved(); // To perform the 1 a ;
fn.call(this); // Executive function , the this Passed in ;
}
}
addEvent(window,'load',function(){
alert('Lee'); // You can perform ;
});
addEvent(window.'load',function(){
alert('Mr.Lee'); // You can perform ;
})
// Register with the custom event function to the switcher to view 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);
2 W3C event handler
// "DOM level 2 events" defines two methods for adding and removing event handlers :addEventListener() and removeEventListener();
// all DOM Both methods are included in the node , And they all receive 3 A parameter : The event name / function / A Boolean value that bubbles or captures (true Said to capture ,false Said the bubbling );
window.addEventListener('load',function(){
alert('Lee');
},false);
window.addEventListener('load',function(){
alert('Mr.Lee');
},false);
// PS:W3C Event binding benefits :1. You don't need to customize it ;2. You can mask the same function ;3. You can set bubbling and trapping ;
window.addEventListener('load',init,false); // The first 1 Time to perform the ;
window.addEventListener('load',init,false); // The first 2 This is blocked ;
function init(){
alert('Lee');
}
// Event switcher
window.addEventListener('load',function(){
var box = document.getElementById('box');
box.addEventListener('click',function(){ // It won't be covered / Mistaken delete ;
alert('Lee');
},false);
box.addEventListener('click',toBlue,false); // The introduction of switching ;
},false);
function toRed(){
this.className = 'red';
this.removeEventListener('click',toRed,false); // Removes the event handler ;
this.addEventListener('click',toBlue,false); // Add event handlers that you want to switch ;
}
function toBlue(){
this.className = 'blue';
this.removeEventListener('click',toBlue,false);
this.addEventListener('click',toRed,false);
}
// Set the bubbling and capture phases
document.addEventListener('click',function(){
alert('document');
},true); // Set to capture ;
document.addEventListener('click',function(){
alert('Lee');
},false); // Set to bubble ;
3 IE event handler
// IE implements two methods similar to DOM :attachEvent() and detachEvent();
// the two methods receive the same parameters: the event name and the function;
// When you use these two sets of functions , The difference between :
// 1.IE Capture is not supported , Bubble only ;
// 2.IE Adding events does not mask duplicate functions ;
// 3.IE In the this Points to the window Rather than DOM object ;
// 4. In traditional events ,IE It's unacceptable event The object's ; But using the attachEvent() But they 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);
}
// PS:IE Capture is not supported ;
// IE Can't block ;
// IE Can't pass this, can call In the past ;
// On traditional bindings ,IE Can't be like W3C That is accepted by reference event object ; But if you use it attachEvent() But they can ;
box.onclick = function(evt){
alert(evt); // undefined;
}
box.attachEvent('onclick',function(evt){
alert(evt); // object;
alert(evt.type); // click;
});
// Compatible with IE and W3C Event switcher function ;
function addEvent(obj,type,fn){ // Add event handler compatibility ;
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 the event target ;
if(evt.target){
return evt.target;
}else if(window.event.srcEleemnt){
return window.event.srcElement;
}
}
4 event object supplementation
1.relatedTarget
// This property can be used in mouseover and mouseout Where did the fetch move in and out of the event DOM object ;
box.onmouseover = function(evt){ // The mouse moving box;
alert(evt.relatedTarget); // Get moving box The previous element ;
}
box.onmouseout = function(evt){ // The mouse moved out box;
alert(evt.relatedTarget); // Get out of box The next element ;
}
// IE Two sets of corresponding properties are provided :fromElement and toElement;
// Compatible with the function
function getEarget(evt){
var e = evt || window.event; // Get the event object ;
if(e.srcElement){ // If the support srcElement, said IE;
if(e.type == 'mouseover'){ // If it is over The event ;
return e.fromeElement; // Use the from;
}else if(e.type == 'mouseout'){ // If it is out;
return e.toElement; // Use the to;
}
}else if(e.relatedTarget){ // If the support relatedTarget, said W3C;
return e.relatedTarget;
}
}
2. The default behavior of blocking events
// 1 The default behavior of a hyperlink is to click and then jump to the specified page ;
// Blocking the default behavior can mask the action of a jump , And implement custom operations ;
// The default behavior of the cancel event is also 1 It's not a standard practice , Is returned false;
link.onclick = function(){
alert('Lee');
return false; // Direct return false, It's not going to jump ;
}
// PS: although return false; You can do that , But there are holes ;
// The first 1: The code must go to the end , This results in the middle of the code after execution , It may not work return false;
// The first 2:return false The custom operation after writing to the top fails ;
// The solution : Block the default behavior first , And you can execute the code later ;
function preDef(evt){ // Cross-browser compatibility prevents default behavior ;
var e = evt || window.event;
if(e.preventDefault){
e.preventDefault(); // W3C, Blocking default behavior ;
}else{
e.returnValue = false; // IE, Blocking default behavior ;
}
}
3. Context menu event contextmenu
// When we right click on the page , Will automatically appear windows Built-in menu ;
// So we can use contextmenu Event to modify the menu we specified ; But only if the default action of right-clicking is cancelled ;
addEvent(window,'load',function(){
var text = docuemnt.getElementById('text');
addEvent(text,'contextmenu',function(evt){ // Add a right-click menu event handler ;
var e = evt || window.event;
preDef(e); // Block the default behavior function ;
var menu = document.getElementById('menu'); // Find the custom menu object ;
menu.style.left = e.clientX+'px'; // Determine customization menu The position on the screen ;
menu.style.top = e.clientX+'px';
menu.style.visibility = 'visible'; // Set customization menu Is visible ;
addEvent(document,'click',function(){ // to document Add a click event handler ;
docuemnt.getElementById('myMenu').style.visibility = 'hidden'; // Will be customized menu hidden ;
});
});
});
4. Uninstall the previous event beforeunload
// This event can help prompt you when you leave the page ;" leave " or " return " operation ;
addEvent(window.'beforeunload',function(evt){
var evt = event || window.event;
var message = ' Whether to leave this page ?';
evt.returnValue = message;
return message;
});
5. Mouse wheel (mousewheel) and DOMMouseScroll
// Used to get the distance of the mouse up and down 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;
if(e.wheelDelta){ // mousewheel The scrolling value of the event is saved at wheelDelta In the ;
return e.wheelDelta;
}else if(e.detail){ // DOMMouseScroll The scrolling value of the event is saved at detail In the ;
return -evt.detail*30; // Keep the computation consistent 1;
}
}