Events (DOM event binding)

event definition 

Event : the natural behavior of the element (it has nothing to do with writing JS code or not) [onclick is not an event, click is an event, and the browser will mount some common events to the private properties of the element object, so that we can realize DOM0 Event binding], when we operate the element, many events of the element will be triggered.
Event binding: Binding method to an event of the current element, the purpose is to make some reactions when an event of the current element is triggered

  Two methods of event binding

1.DOM0-level event binding
curEle.οnclick=function(){};
2.DOM2-level event binding
Standard browser: curEle.addEventListener('click',function(){},false)
IE6-8: curEle. attachEvent('onclick', function(){})

DOM0 event

Summary of Common Events

[PC side]

Commonly used events for form elements

  • blur: lose focus
  • focus: get the focus
  • change: content changes
  • select: selected event

Keyboard Common Event Behavior

  • keydown: keyboard pressed
  • keyup: raise the keyboard
  • keypress: The keyboard is pressed (Chinese input method cannot be triggered, but it can be triggered in English state, because the text is entered into the text box)

Mouse Common Event Behavior

click: click (not click)
dblclick: double click (trigger two click events consecutively within 300ms)
mouseover: the mouse slides over
mouseout: the mouse slides out mouseenter
: the mouse enters mouseleave
: the mouse leaves
mousedown: the mouse presses (left button)
mouseup : Raise the left mouse button
mousewheel: Scroll the mouse wheel

Other Common Event Behaviors'

  • load: loaded successfully
  • error: failed to load
  • scroll:
  • resize: size change event: window.onresize: trigger the event when the browser window changes size

[Mobile]

Mobile keyboards are generally virtual keyboards. Although there are keydown and keyup, they are not compatible. Input events are used instead of
mobile terminals without a mouse, so mouse events are very poorly compatible on mobile terminals, and mouse events are basically unavailable on
mobile terminals. Some events are done by fingers, so it has unique finger events
- single finger event: touchstart touchmove touchend touchcancel
- multi-finger event: gesturestart gestuerchange gestuerend.....

There are still many events on the mobile terminal that are completed by hardware: mobile phone sensors, gyroscopes, gravity sensors, etc. are
compatible with click events, which use click as a click (there will be a 300MS delay event)

event object

A rigorous description of the following event binding: Based on the binding method of DOM0-level events, a method is bound to the click event of the box. When the click event is manually triggered, the bound method will be executed
box.onclick=function(e){
arguments[0]===e;//=>e is the event object
e=e||window.event;( compatible version to get the event object)
};
When an event behavior of an element is triggered, not only will the previously bound method be executed, but also a value will be passed to the bound method (by default by the browser), we put The passed value is called an event object : (standard browser)
- This value is an object type value, which stores many properties and methods, -
These stored values ​​​​are the basic information of the current operation , for example: mouse Location, type of behavior that is triggered. . . . [ Only related to this operation, there is only one event object in a page]

The mechanism of the event object under IE6-8
- when the method is triggered and executed, the browser does not pass the event object as a value to the function; (e is undefined)
- the event object under IE6-8 needs us to get it through window.event

Mouse event object (mouseevent)

  • clientX/clientY:当前窗口左上角 X/Y coordinates of the current mouse trigger point distance
  • pageX/pageYBODY左上角: X/Y coordinates of the distance from the current mouse trigger point (these two properties are not available in IE6-8)
    兼容处理
  box.onckick=function(e){
        if(typeof e==='undefined'){
        e=window.event;   //->处理e
        //->pageX/pageY
        e.pageX=e.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft);
        e.pageY=e.clientY+(document.documentElement.scrollTop||document.body.scrollTop);
        //->target
        e.target=e.srcElement;
        //->preventDafault
        e.preventDefault=function(){
            e.returnValue=false;
        };
        //=>stopPropagation
        e.stopPropagation=function(){
            e.cancelBubble=true
        }
        }
        }//该兼容比较完整,当处理一个简单兼容时可简单处理

· type: the type of the current triggering event
· target: the source of the event (the element currently being operated by the mouse) (IE6-8 does not have this attribute, use the attribute srcElement to represent the event source) · preventDefault:
function: prevent the default behavior of the event; ( IE6-8 does not have this method, use returnValue=false to handle)
stopPropagation: prevent the event from bubbling [IE6-8 is not compatible, use cancelBubble=true to handle]

Keyboard event object (keyboardEvent)

· code: which keyboard key is currently pressed [IE6-8 does not have this attribute] the key attribute is the same as code, but the storage format is different
keyCode: the code value of the current key is stored (most keys have their own code value )
which: Same as keyCode, it is also the code value of the current key (which is not compatible with IE6-8).
   These code values ​​need to be remembered (delete: 8, carriage return: 13, space: 32, tab: 9,)

Finger event object (TouchEvent)

touches&&changedTouches&&targetTouches: stores the position information of each finger operation on the current screen
- touches: we can only get relevant information when the finger is on the screen, after the finger leaves, we cannot get finger information through touches in the touchend event - changedTouches
: the finger is on the screen When on the screen, you can get relevant information like touches, and you can also record the location information of the finger when you leave the screen after leaving the screen (the most commonly used)

touchesEvent
    type:'touchStart',
    target:事件源,
    touches:
    0:{
    clientX:xxx,
    clientY:xxx,
    pageX:xxx,
    pageY:xxx,
    .....
    }
    ...
    lentth:1
    chan

 DOM2 event binding

   //=>标准浏览器
    oBox.addEventLister('click',function(e){
    //this:obx
    },false)
    //false=>让事件在冒泡传播时执行
   //true=>让事件在捕获阶段执行(非常少见)
//=>IE6-8浏览器
        oBox.attachEvent('onclick',function(e){
        //e:事件对象,不同于DOM0级事件,浏览器会默认将事件对象传递进来,与window.event的值相同,因此对于:pageX/pageY/target...等依旧存在兼容;
        })
        //=>绑定的方法都是在冒泡传播阶段执行

The difference between DOM0 and DOM2 event binding

The principle of DOM0 event binding
The process of assigning a value to a private attribute (onXXX) of the current element; (the default value of the attribute before is null, if we assign a function, it is equivalent to binding a method) When we
assign Success (assign a function), at this time, the browser will associate the DOM element with the assigned function, and establish the behavior monitoring of the DOM element. When a certain behavior is triggered by the user, the browser will execute the assigned function;

Features of DOM0 event binding:
Only DOM elements have this private attribute (onxxx event private attribute), the method we assign is called event binding, otherwise it belongs to setting custom attributes
When removing event binding, we only It needs to be assigned a value of null;
In the DOM0 event binding, only one method can be bound to a certain event behavior of the current element, and multiple methods can be bound, and the last binding will replace the previous binding

The principle of DOM2 event binding

The addEventListener/attachEvent method used in DOM2 event binding is defined on the prototype of the built-in class eventTarget. When we call it, we must first find this  method through the prototype chain, and then execute the effect of event binding. The browser
will Create an event pool (event queue) for a certain event behavior of the current element [the browser has a unified event pool, and the behaviors bound to each element are placed here, distinguished by related signs], when we pass addEventListener/attachEvent When event binding is performed, the bound method will be placed in the event pool;
When a certain behavior of the element is triggered, the browser will return to the corresponding event pool, and put all the methods currently in the event pool in order implement

features

All behaviors supported by DOM0 can be used in DOM2, and DOM2 also supports event behaviors that DOM0 does not have (this is more general)
(core) [The browser will mount some common events to the private properties of the element object, so that we can Realize DOM0 event binding, DOM2: All events that browsers set for elements can be used in DOM2]
   For example: onDOMContentLoaded (all DOM0 and DOM2 of IE6-8 do not support)

   onDOMContentLoaded//The DOM structure in the current browser is loaded, and this event will be triggered

In DOM2, multiple different methods can be bound to an event behavior of the current element (because all bound methods are placed in the event pool);

Removal of events: event type, binding method, and propagation phase are completely consistent before removal can be completed (so when binding methods, try not to use anonymous functions, otherwise it is difficult to remove)

//=>ON:给当前元素的某个事件绑定某个方法
   var on = function (curEle, type, fn) {
   if (document.addEventListener) {
       //=>标准浏览器
        curEle.addEventListener(type, fn, false);
       return;
   }
  //=>IE6~8
  curEle.attachEvent('on' + type, fn);
};
//=>OFF:移除当前元素某个事件绑定的某个方法
var off = function (curEle, type, fn) {
    if (document.removeEventListener) {
        curEle.removeEventListener(type, fn, false);
        return;
    }
    //=>IE6~8
    curEle.detachEvent('on' + type, fn);
};

The difference between dom0 and dom2

dom0: the same event will only be executed once

dom2: The same event can be listened to multiple times 

event monitoring 

1. Function:

​ If it is an ordinary event binding, only one event handler can be bound for the same event type

​ If the same type is bound to multiple event handlers, the event bound later will overwrite the event bound before

2. Grammar:

​ Label object.addEventListener(event type, event handler)

​ The third parameter: true / false (default value)

oDiv1.addEventListener('click' , function(){} , true)

3. How to get the event

​ Bubble: start from the child, execute to the parent

​ Capture: start from the parent and execute to the child

​ The browser defaults to the bubbling execution method

​ You can set the acquisition method through the third parameter of addEventListener

​ The default value is false, which is the bubbling method, and true, which is the capturing method

​ In general actual projects, if the third parameter is not defined, the default method is used

​ The lower version of IE only supports bubbling, does not support capture, will not report errors, and will only execute in the order of bubbling

<div>123</div>
<script>
    var oDiv = document.querySelector('div');
    var fun4 = function(){
        console.log('abc');
    }

    oDiv.addEventListener('click' , fun1);
    oDiv.addEventListener('click' , fun2);
    oDiv.addEventListener('click' , fun3);
    oDiv.addEventListener('click' , fun4);
    oDiv.addEventListener('click' , function(){console.log('别想删我')});

    // 可以删除
    oDiv.removeEventListener('click' , fun1);
    oDiv.removeEventListener('click' , fun4);
    // 不能删除
    oDiv.removeEventListener('click' , function(){console.log('别想删我')});
    function fun1(){
        console.log(123);
    }

    function fun2(){
        console.log(456);
    }


    function fun3(){
        console.log(789);
    }
    //控制台结果:fun1 fun4 被删除 其他都执行
</script>

Guess you like

Origin blog.csdn.net/Cc200171/article/details/124972314