8, DOM -- events

1, Event binding

1.1 HTML tag event binding

Binding an event in an HTML tag is equivalent to executing a piece of code in the tag

	
	<button onclick="show();print();alert('123')" id="btn1">html Tag event binding</button>
			
	be careful:
		1,adopt HTML Tag binding event functions essentially run multiple lines within a tag JS code.
		
		2,Bind the event function in the tag, and the this refer to window Object.
		
		3,Bind the event function in the tag, and the event function can pass in parameters.
					Any parameter can be passed in.
					Can also be passed in this object,Represents the current label object.
			
1) Binding event functions through HTML tags is essentially running multiple lines of JS code within tags
 <script>
 
            function show(){
                alert('456')
            }

            function show2(){
                alert('789')
            }

</script>

<body>
    
    <button onclick="alert('123');show();show2()"> Click on me</button>
    
</body>

2) Bind the event function in the tag. this in the event function refers to the window object
    <script>
                function show(){
                   console.log(this)
                }



    </script>
</head>
<body>
    
    <button onclick="show();"> Click on me</button>
</body>    

3) Bind the event function in the tag. The event function can pass in any parameter or this object.
>>>>>>You can pass any parameter to the bound function
 <script>
                function show(str){
                   console.log(str); 
                }

         

    </script>
</head>
<body>
    
    <button onclick="show('123');"> Incoming string</button>

</body>

>>>>>>You can pass in this object to the bound function. This object here refers to the label itself.
 <script>
              function show(obj){
                 console.log(obj); 
              }

    </script>
</head>
<body>    
    <button onclick="show(this);"> afferent this</button>
</body>

1.2 JS event binding

	
		1,Bind an anonymous function
				    elem.onclick=function(){
				        alert("1")
				    }


		2,Bind a declared function	
					function show(){
					  console.log('show');
					}
					
					//Bind a declared function
				    elem.onclick=show;
	
	be careful:		
		1,JS Event binding, in event function this Refers to the bound object.

		2,Only one response function can be bound for an event, not multiple.
		   If multiple are bound, the response function bound later will overwrite the previous response function.	
		
		3,JS Event binding,In event functions this Refers to the bound element.
				
1) JS event binding
<body>
    
    <button > Bind anonymous function</button>
    <button > Bind declared functions</button>
</body>
    <script>


            /** Bind anonymous function*/
            var btn=document.getElementsByTagName("button")[0]
            btn.onclick=function(){
                alert("123")
            }

            /** Bind declared functions*/
            function show(){
                alert("123")
            }
            var btn1=document.getElementsByTagName("button")[1]
            btn1.onclick=show;
            

    </script>

2) Only one response function can be bound for an event, not multiple. Otherwise, it will be overwritten
<body>
    
    <button> Click on me</button>
    
</body>

<script>

    var btn=document.getElementsByTagName("button")[0];
    
    btn.onclick=function(){
        alert("0")
    }
    btn.onclick=function(){
        alert("1")
    }
	
	//The previously bound event function will be overwritten
    btn.onclick=function(){
        alert("2")
    }
</script>
   

3) JS event binding. this in the event function refers to the bound element

1.3 event monitoring

	
	+++ IE8 Above browser event listening
	
				elem.addEventListener("click",function(){},false);
										First parameter:String for the event, no need on
										Second parameter:Callback function,This callback function is called when the event is triggered
										Third parameter:Default to false,Indicates whether the capture phase is triggered.
			
							1,IE8 Above browser support
							
							2,You can bind multiple response functions for an event at the same time.
				     		   When the event is triggered, the response function will be executed in positive order according to the binding order.
							
							3,In event functions this Refers to the element itself


	+++ IE8 Monitor the browser and the following events
	
				elem.attachEvent("onclick",function(){});
										First parameter:String for the event, want on
										Second parameter:Callback function,This callback function is called when the event is triggered
							
							1,IE8 And the following browser support
							
							2,You can bind multiple response functions for an event at the same time.
				     		   When the event is triggered, the response function will be executed in reverse order of binding.
							
							3,In event functions this refer to window. 
				

	+++ Event listening compatibility processing
	
			    function bind(obj,eventStr,calFun){
	                    if(obj.addEventListener){
	                        //Compatible with IE8 and above browsers
	                        obj.addEventListener(eventStr,calFun);
	                    }else{
	                        //Compatible with IE8 and the following browsers
	                        obj.attachEvent("on"+eventStr,function(){
	
	                            //Change this object in function
	                            calFun.apply(obj);
	                        })
	                    }
                 }

1) addEventListener event listener
>>>>>>Multiple response functions can be bound. Execute in positive order (only supports browsers above IE8)
<body>    
    <button > event listeners </button>
</body>
    <script>


            var btn=document.getElementsByTagName("button")[0]
           
            btn.addEventListener("click",function(){
                alert("123")
            })
            btn.addEventListener("click",function(){
                alert("456")
            })
            btn.addEventListener("click",function(){
                alert("789")
            })

    </script>
2) attachEvent event listener
>>>>>>Multiple response functions can be bound. Execute in reverse order (only IE8 and the following browsers are supported)
<body>
    
    <button > event listeners </button>
</body>
    <script>


            var btn=document.getElementsByTagName("button")[0]
           
            btn.attachEvent("onclick",function(){
                alert("123")
            })
            btn.attachEvent("onclick",function(){
                alert("456")
            })
            btn.attachEvent("onclick",function(){
                alert("789")
            })


    </script>

3) Listening event compatibility processing
	
	If event listeners want to handle compatibility,
	Then we need to consider:addEventListener and attachEvent of this Point to the problem.
					
					1,addEventListener Medium this Refers to the element itself
					2,attachEvent Medium this refer to window Object.
			
		 function bind(obj,eventStr,calFun){
                    if(obj.addEventListener){
                        //Compatible with IE8 and above browsers
                        obj.addEventListener(eventStr,calFun);
                    }else{
                        //Compatible with IE8 and the following browsers
                        obj.attachEvent("on"+eventStr,function(){

                            //Change this object in function
                            calFun.apply(obj);
                        })
                    }
                }
>>>>>>Case
<body>
    
    <button > event listeners </button>
</body>
    <script>


            /** Event listening compatibility processing*/
            function bind(obj,eventStr,calFun){
                    if(obj.addEventListener){
                        //Compatible with IE8 and above browsers
                        obj.addEventListener(eventStr,calFun);
                    }else{
                        //Compatible with IE8 and the following browsers
                        obj.attachEvent("on"+eventStr,function(){

                            //Change this object in function
                            calFun.apply(obj);
                        })
                    }
             }

             var btn=document.getElementsByTagName("button")[0]
            
             bind(btn,"click",function(){
                 alert("123")
             })

             bind(btn,"click",function(){
                 alert("456")
             })

             bind(btn,"click",function(){
                 alert("789")
             })


    </script>

2, Event object

	Event object(event): 
			 
		  1) All information related to the current event is encapsulated in the event object. For example: mouse coordinates, key values, etc
		 
		  2) stay IE8 Above browser
		  	    	 When the event callback function is triggered,
		  	   		 Each time, the browser passes an event object as an argument to the callback function.
		  	   		     
		  3) stay IE8 And the following browsers
					 Event objects are treated as window Properties to save.
					 

1.1 use of event object

1) In browsers above IE8, the event object will be passed into the event callback function as an argument

When the event callback function is triggered, the browser will pass an event object into the callback function as an argument. Since arguments will receive all parameters, we print the arguments object to see the incoming event object.

         var box1=document.getElementById("box1")
         box1.onclick=function(){
             console.log(arguments[0])
         }
            


We can define a variable to receive the incoming event object

     var box1=document.getElementById("box1");
     box1.onclick=function(event){
            console.log(event)
     }
        

2) In IE8 and below browsers, event objects are saved as window properties.
         var box1=document.getElementById("box1");
         box1.onclick=function(){
         	
         	//MouseEvent {isTrusted: true, screenX: 339, screenY: 517, clientX: 97, clientY: 32, ...}
             console.log(window.event);
         }

3) Compatibility handling of event objects
	
	+++ Mode 1:
			   var box1=document.getElementById("box1");
			   box1.onclick=function(event){
					
				   //Compatibility processing	
			       if(!event){
			           event=window.event;
			       }
			
			       console.log(event)
			   }
	   
	
	+++ Mode II:
  				var box1=document.getElementById("box1");
                box1.onclick=function(event){
                
				    //Compatibility processing	
                    event=event || window.event;

                    console.log(event)
                }	   
                

1.2 mouse attribute of event object (obtain mouse coordinates through event object)

	
	+++ Gets the coordinates of the mouse relative to the window
					
				clientX	
				clientY	
						Obtain the horizontal and vertical coordinates of the mouse relative to the window
					    (0,0)Zero is always at the top left of the browser.
					    
								    Note: use this property to implement[ DIV [element moves with mouse],
								         If the page does not have a scroll bar, it can be implemented.
								         If the page has a scroll bar, it cannot be implemented. The reason is that the coordinates obtained through this attribute are relative to the window, not the page.

		 
	 
	
	+++ Gets the coordinates of the mouse relative to the page
				
				Mode 1:	
						pageX
						pageY   
								Obtain the horizontal and vertical coordinates of the mouse relative to the page.
								(0,0)Zero is always at the top left of the page.
								Only support IE8 Above browser

				Mode II:
						clientX	+ scrollLeft	 
						clientY	+ scrollTop 
								Obtain the horizontal and vertical coordinates of the mouse relative to the page.
								Compatible with all browsers.
	 								
		 Note: an identity is hidden here, that is
					event.clientX + document.body.scrollLeft  = pageX
					event.clientY + document.body.scrollTop   = pageY



1) Gets the coordinates of the mouse relative to the window
       //Binding a move event to a document
       document.onmousemove=function(event){
			
		   //Event object compatibility handling	
           event=event || window.event;
           
           //Obtain the horizontal and vertical coordinates of the mouse relative to the window
           console.log("x:"+event.clientX+"  ,y:"+ event.clientY);

       }

2) Gets the coordinates of the mouse relative to the page
>>>>>>Div element moves with the mouse [implemented by pageX and pageY] [only supports browsers above IE8]
	
	pageX,pageY You can obtain the coordinates of the mouse relative to the page, so we can set the movement of the element by obtaining this value.
	However, this property only supports IE8 Above browser.
	
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>

            window.onload=function(){

                var box1=document.getElementById("box1");

                //Bind mobile events to html tags
                document.documentElement.onmousemove=function(event){

                    event=event || window.event;

                    var left=event.pageX;
                    var top=event.pageY ;

                    
                    // var left=event.clientX + document.body.scrollLeft;
                    // var top=event.clientY + document.body.scrollTop;

                    box1.style.left=left+"px";
                    box1.style.top=top+"px";

                }

            }

    </script>
</head>
<body>
    <div id="box1" style="width:100px;height:100px;border:1px solid red;position:absolute;"></div>
</body>
</html>

>>>>>>Div element moves with the mouse [compatibility processing, support all browsers]
	
	We use clientX,clientY The coordinates obtained are the coordinates of the mouse relative to the browser.
	The left and right positioning of elements is relative to the coordinates of the page.  
	There is an equation hidden here, that is
						clientX+scrollLeft  = pageX
						clientY+scrollTop   = pageY
							
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>

            window.onload=function(){

                var box1=document.getElementById("box1");

                //Bind mobile events to html tags
                document.documentElement.onmousemove=function(event){

                    event=event || window.event;
                    
                    var left=event.clientX + document.body.scrollLeft;
                    var top=event.clientY + document.body.scrollTop;

                    box1.style.left=left+"px";
                    box1.style.top=top+"px";

                }

            }

    </script>
</head>
<body>
    <div id="box1" style="width:100px;height:100px;border:1px solid red;position:absolute;"></div>
</body>
</html>

1.3 keyboard properties of event object

	altKey		Returns when the event is triggered,"ALT" Whether it is pressed.
	ctrlKey		Returns when the event is triggered,"CTRL" Whether the key is pressed.
	metaKey		Returns when the event is triggered,"meta" Whether the key is pressed.
	shiftKey	Returns when the event is triggered,"SHIFT" Whether the key is pressed.
	
	button		Returns which mouse button was clicked when the event was triggered.

       
        
        document.onkeydown=function(event){

            if(event.altKey){
                alert("alt Key pressed")
                return;
            }


            if(event.ctrlKey){
                alert("ctrl Key pressed")
                return;
            }

            if(event.shiftKey){
                alert("shift Key pressed")
                return;
            }


            if(event.metaKey){
                alert("meta Key pressed")
                return;
            }
        }

1.4 drag cases

1) Case 1

Disadvantages: when dragging elements, you can only drag the upper left corner

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    
    <style>
        
        div{
            width:100px;
            height:100px;
            background-color: red;

            position: absolute;
        }

    </style>
</head>
<body>
    
    <div></div>
</body>

<script>

    
    var div=document.getElementsByTagName("div")[0];
    
    //Add mouse down event to DIV
    div.onmousedown=function(){
        
        //Bind mouse movement event when mouse is pressed
        document.onmousemove=function(event){
            event=event||window.event;

            //Gets the coordinates of the mouse relative to the page
            var x=event.pageX;
            var y=event.pageY;

            div.style.left=x+"px";
            div.style.top=y+"px";
        }

        //Bind mouse lift event when mouse is pressed
        document.onmouseup=function(){
             //Cancel move event
             document.onmousemove=null;
            
            //Cancel mouse up event
            document.onmouseup=null;
        }
    }

</script>
</html>

2) Case 2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    
    <style>
        
        div{
            width:100px;
            height:100px;
            background-color: red;

            position: absolute;
        }

    </style>
    

</head>
<body>
    
    <div></div>
</body>

<script>

    
    var div=document.getElementsByTagName("div")[0];
    
    //Add mouse down event to DIV
    div.onmousedown=function(){
        
        //Coordinates of the mouse relative to the page - offset of the element 
        var ox=event.pageX-div.offsetLeft;
        var oy=event.pageY-div.offsetTop;
        
        //Bind mouse movement event when mouse is pressed
        document.onmousemove=function(event){
            
            event=event||window.event;

            //Gets the coordinates of the mouse relative to the page
            var x=event.pageX-ox;
            var y=event.pageY-oy;

            div.style.left=x+"px";
            div.style.top=y+"px";
        }

        //Bind mouse lift event when mouse is pressed
        document.onmouseup=function(){
             //Cancel move event
             document.onmousemove=null;
            
            //Cancel mouse up event
            document.onmouseup=null;
        }


    }

</script>
</html>

3) Case 3 (encapsulation based on case 2)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    
    <style>
        
        *{
            margin:0px;
            padding:0px;
        }
       

        .dd{

            width:100px;
            height:100px;
            background-color: red;

            position: absolute;

        }

    </style>
    

</head>
<body>
    
    <div class="dd">box1</div>
    <div class="dd">box2</div>
    <div class="dd">box3</div>

</body>

<script>

    
    


    function drag(elem){
            
        //Add mouse down event to DIV
            elem.onmousedown=function(){

                    
                    //Coordinates of the mouse relative to the page - offset of the element 
                    var ox=event.pageX-elem.offsetLeft;
                    var oy=event.pageY-elem.offsetTop;


                    //Add a mouse movement event to the document
                    document.onmousemove=function(event){
                        
                        event=event||window.event;

                        //Gets the coordinates of the mouse relative to the page
                        var x=event.pageX-ox;
                        var y=event.pageY-oy;

                        elem.style.left=x+"px";
                        elem.style.top=y+"px";
                    }

                    //Add a mouse up event to the document
                    document.onmouseup=function(){
                        //Cancel move event
                        document.onmousemove=null;
                        
                        //Cancel mouse up event
                        document.onmouseup=null;
                    }
                }
    }
    

    var box1=document.getElementsByClassName("dd")[0]
    drag(box1)


    var box2=document.getElementsByClassName("dd")[1]
    drag(box2)

    var box3=document.getElementsByClassName("dd")[2]
    drag(box3)

</script>
</html>

3, Bubbling of events

	
	+++ Event Bubbling 
				1,The so-called bubbling refers to the upward conduction of event trigger.
				   When the event of a descendant is triggered, the same event of its ancestor will also be triggered.
				
				2,Event bubbling has two sides. You can't just say good or bad.
							
	
	+++ Prevent event bubbling
				  box2.onclick=function(event){
				 
                            //Cancel bubbling
                            event=event || window.event;
                            event.cancelBubble=true; 

                            alert("I am box2 Click response function");
                    }	
                   		
                   	be careful:Preventing bubbling is to prevent the event bubbling of child elements,
                   	     Therefore, preventing bubbling should be added to the event function bound to the child element.
                   	    		
1) Event bubbling

The so-called event bubbling means that when I click box2, the box2 click event is triggered. At the same time, the same event of box1, the ancestor element of box2, is triggered.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>

        .box1{
            width:500px;
            height:500px;
            background-color: red;
        }

        .box2{
            width:300px;
            height:300px;
            background-color: blue;
        }

     

    </style>

    <script>

            window.onload=function(){
                    var box1=document.getElementsByClassName("box1")[0];
                    var box2=document.getElementsByClassName("box2")[0];

                    box1.onclick=function(){
                        alert("I am box1 Click response function")
                    }

                    box2.onclick=function(){
                            alert("I am box2 Click response function");
                    }

              


            }

    </script>
</head>
<body>
    <div class="box1">
        <div  class="box2"></div>
    </div>
</body>
</html>

2) Prevent event bubbling

Preventing event bubbling means preventing the event triggering of the descendant element box2 from causing the event triggering of the ancestor element box1. At this time, clicking the descendant element box2 will only trigger the box2 binding event.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>

        .box1{
            width:500px;
            height:500px;
            background-color: red;
        }

        .box2{
            width:300px;
            height:300px;
            background-color: blue;
        }

     

    </style>

    <script>

            window.onload=function(){
                    var box1=document.getElementsByClassName("box1")[0];
                    var box2=document.getElementsByClassName("box2")[0];

                    box1.onclick=function(){
                        alert("I am box1 Click response function")
                    }

                    box2.onclick=function(event){

                            //Cancel bubbling
                            event=event || window.event;
                            event.cancelBubble=true; 

                            alert("I am box2 Click response function");
                    }

              


            }

    </script>
</head>
<body>
    <div class="box1">
        <div  class="box2"></div>
    </div>
</body>
</html>

1.4 significance of bubbling

	1,The element is not bound to an event, and the function can also trigger an event.
	   It's just that there is no event callback function to handle.

	2,If an element has no descendants, the event trigger of the element is its own event trigger.
	   If an element has a descendant element, the event triggering of the element may actually be caused by the event triggering bubble of the descendant element (the descendant element pointed by the mouse).

>>>>>>Take the case of [DIV element moves with mouse] as an example
	
	to document Object binding mouse movement event callback function.
	
	When the mouse moves over the red box, document The object's move event callback function is also called.
	In essence, it is triggered by the bubble of the mouse movement event in the red box document Mouse movement event.
	
	If we stop the red box from bubbling,
	Then the mouse will move on the red box without triggering document Mouse movement event.
	
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>

        *{
            margin:0px;
            padding:0px;
        }

        .box1{
            width:500px;
            height:500px;
            background-color: red;
        }

        .box2{
            width:100px;
            height:100px;
            background-color: blue;
            position: absolute;
        }

     

    </style>

    <script>

            window.onload=function(){
                  
                    var box2=document.getElementsByClassName("box2")[0];

                    //Bind the mouse movement event callback function to the document object
                    document.onmousemove=function(event){
                        
                        //Compatibility processing
                        event=event||window.event;

                        var left=event.clientX + document.body.scrollLeft;
                        var top=event.clientY + document.body.scrollTop;

                        box2.style.left=left+"px";
                        box2.style.top=top+"px";
                    }

                    //Prevent mouse movement event bubbling of box1
                    var box1=document.getElementsByClassName("box1")[0];
                    box1.onmousemove=function(event){

                            event=event||window.event;
                            event.cancelBubble=true; 
                    }
      
            }

    </script>
</head>
<body>
   
    <div class="box1"></div>
    <div class="box2"></div>

</body>
</html>

4, Delegation of events

	
	+++ event delegation 
			1,Event delegation takes advantage of the event bubbling mechanism. Handle the events of descendant elements through the bound event function of ancestor elements.
			
			2,Event delegation can reduce the number of event bindings. Binding only once can be applied to multiple elements. Improve the efficiency of operation.
			
			3,Uniformly bind events to the common ancestor elements of elements, and the events of descendant elements will be triggered. Through bubbling, the events of ancestor elements will also be triggered.
			   In this way, events can be handled through the event function of the ancestor element.
			

	
	+++ Implementation of event delegation
			1,Uniformly bind events to the common ancestor elements of the element.
			2,Pass in event function event.target To access the actual object that triggered the event.
						(The actual object refers to the object pointed by the mouse. Triggered by an event for this object,And bubble upward, resulting in the event trigger of the ancestor element)
					  		
					        ul.onclick=function(event){
					
					            event=event||window.event;
					            console.log(event.target)
					            
					            //Via event Target to access the actual object that triggers the event
					            alert(event.target.innerHTML)
					        }
		
1) Source of event delegation
	for Loop to bind event functions to elements,Binding times too many,It will cause a waste of resources.
	

Set the click event for the a tag. Binding can only be repeated. The label can only be set to an existing event a. For the newly added a tag, you can only add it again.

<body>
    
    <button> Add hyperlink</button>
    <ul>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
    </ul>
</body>

<script>


        //Click the button to add a li tag
        var btn=document.getElementsByTagName("button")[0];
        var ul=document.getElementsByTagName("ul")[0];
        
        btn.onclick=function(){

            var li=document.createElement("li");
            li.innerHTML='<a href="javascript:;">Baidu</a>';

            ul.appendChild(li);
        }


        //Add event to a tag
        var aElems=document.querySelectorAll("ul li a");
        for(var i=0;i<aElems.length;i++){
            aElems[i].onclick=function(){
                alert("123");
            }
        }

</script>
</html>

2) Event delegation
	1,Bind an event to the common ancestor element of the element,
	  When an event of a child element is triggered, the event function of the ancestor element is triggered by bubbling. It is handled through the event function of the ancestor element.
	
	2,In the event function, we can event.target To manipulate the actual object that triggers the event.
	
>>>>>>Event delegation
<body>
    
    <button> Add hyperlink</button>
    <ul>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
    </ul>
</body>

<script>

        //event delegation 
        var ul=document.querySelectorAll("ul")[0];
        ul.onclick=function(event){

            event=event||window.event;
            console.log(event.target)
            
            //We can use event Target to access the actual object that triggers the event
            alert(event.target.innerHTML)
        }

</script>

>>>>>>Analysis
	
	a The click event of the tag is triggered by bubbling, resulting in the ancestor element ul The click event of is triggered.
	We are ul In the bound click event,
	Can pass event.target To access the actual object that triggers the event (that is, the object pointed by the mouse).
	
3) Event delegation case
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <button> Add hyperlink</button>
    <ul>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
        <li><a href="javascript:;">Baidu</a></li>
    </ul>
</body>

<script>
		
		//Event delegation mechanism
		//Bind events to the common ancestor elements of the a tag
		//When the click event of a tag is triggered, the event function of the ancestor element will be triggered by bubbling.
		//We handle it accordingly through the event function of the ancestor element.
        var ul=document.querySelectorAll("ul")[0];
        ul.onclick=function(event){

            event=event||window.event;
            console.log(event.target)
            
            //Via event Target to access the actual object that triggers the event
            alert(event.target.innerHTML)
        }


        //Click the button to add a li tag
        var btn=document.getElementsByTagName("button")[0];
        var ul=document.getElementsByTagName("ul")[0];
        
        btn.onclick=function(){

            var li=document.createElement("li");
            li.innerHTML='<a href="javascript:;">Baidu</a>';

            ul.appendChild(li);
        }

</script>
</html>

5, Propagation of events

4.1 communication mode of the event

	
	Microsoft and Netscape have different understandings about the spread of the incident.
	
	1) Microsoft believes that the event should be spread from inside to outside.
	   		When the event is triggered, the event of the current element (the element pointed by the mouse) is triggered first,
	   		Then it propagates to the ancestor element of the current element. That is, the event is executed in the bubbling phase.

	   
	2) Netscape believes that events should be spread from outside to inside.
	   		When an event is triggered, the event of the outermost ancestor element of the current element (the element pointed to by the mouse) is triggered first,
	   		It then propagates inward to future generations.
		
		

	3) W3C Integrated two company solutions. Event propagation is divided into three stages.
					
		1,Capture phase
				In the capture phase, events are captured from the outermost ancestor element to the target element,
				However, by default, no event is triggered at this time.
				
		2,Target stage
				The event captures the target element, which is the target phase.
				The end of capture begins to trigger an event on the target element.
		
		3,bubbling phase 
				Event triggers are passed from the target element to its ancestor element.
	
	[Capture from outside to inside and trigger from inside to outside. By default, events are triggered in the target phase and then bubble outward.]	
		

4.2 manually set the stage of event triggering

	
	We can pass addEventListener The third parameter to set the stage of event triggering.
	
	1) If we want the event to trigger in the capture phase,be
				elem.addEventListener("click",function(){},true);

	2) If we want the event to be triggered in the target phase (the default is),be
				elem.addEventListener("click",function(){});  //No. The third parameter defaults to false
				elem.addEventListener("click",function(){},false);
	
>>>>>>Set event trigger in capture phase
		
		click box3,First, enter the capture phase box3 The ancestor element of begins to capture.
		Because the capture phase trigger event is set, it is triggered first box3 Ancestral element of box1 Events, and then box2 event, box3 event.
		
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>

        .box1{
            width:500px;
            height: 500px;
            background-color: red;
        }

        .box2{
            width:400px;
            height: 400px;
            background-color: blue;
        }

        .box3{
            width:300px;
            height: 300px;
            background-color: pink;
        }

    </style>
</head>
<body>

    <div class="box1">
        <div class="box2">
            <div class="box3"></div>
        </div>
    </div>

</body>
    <script>


            var divs=document.getElementsByTagName("div");
            
            var box1=divs[0];
            var box2=divs[1];
            var box3=divs[2];

             box1.addEventListener("click",function(){
                 alert("I am box1")
             },true)

             box2.addEventListener("click",function(){
                 alert("I am box2")
             },true)

             box3.addEventListener("click",function(){
                 alert("I am box3")
             },true)

    </script>

<script>

 

 
</script>
</html>

>>>>>>Set the event trigger in the target phase (the default is)
		
		click box3,First enter the capture phase, from box3 Ancestral element of box1 Start capture. until box3. 
		Then trigger box3 Events.
		Then bubble.
		
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>

        .box1{
            width:500px;
            height: 500px;
            background-color: red;
        }

        .box2{
            width:400px;
            height: 400px;
            background-color: blue;
        }

        .box3{
            width:300px;
            height: 300px;
            background-color: pink;
        }

    </style>
</head>
<body>

    <div class="box1">
        <div class="box2">
            <div class="box3"></div>
        </div>
    </div>

</body>
    <script>


            var divs=document.getElementsByTagName("div");
            
            var box1=divs[0];
            var box2=divs[1];
            var box3=divs[2];

             box1.addEventListener("click",function(){
                 alert("I am box1")
             },false)

             box2.addEventListener("click",function(){
                 alert("I am box2")
             },false)

             box3.addEventListener("click",function(){
                 alert("I am box3")
             },false)

    </script>

<script>

 

 
</script>
</html>

1.1 mouse / keyboard properties

1) clientX and clientY obtain the coordinates of the mouse relative to the window
2) pageX and pageY obtain the coordinates of the mouse relative to the page

Added by umol on Wed, 05 Jan 2022 14:23:58 +0200