Event review in JavaScript

Source: Internet
Author: User

The event actually touches the first time you learn JavaScript, and a very simple line of code alert(‘Hello JavaScript!!!‘) interprets what is an event. What is the event? Events are a very, very important method in browser-based language JavaScript, and this syntax is everywhere. What is an event? In JavaScript, an event can be understood as something that happens, and the event object records all the data in the process.

1. Compatibility handling of events

It is well known that many browsers are now divided into standard browser Camp Chrome, Firefox, etc., non-standard browser is the representative of IE, in writing code when it is necessary to be careful of their compatibility between the problem, this is the norm. Events are no exception to these compatibility issues.

The most important thing to understand an event is the event object mentioned above:
    • Ie/chrome:event is a built-in object
    • FireFox: The event object is passed in by the first parameter of the event function
Document.onclick = function(EV){    //The content displayed in IE Firefox is completely different, so events need to be processedalert (event);//In order to be compatible with various browsers can use the following wording    varEV = EV | | window.event;varstr ="';vari =0;//The EV Event object holds all the information during the event, iterates through the information in the event object, and outputs to the page to observe all the information     for(varattrinchEV) {++i; str + = i +'. '+ attr +'---> '+ ev[attr] +' <br> '; }//Add information to the pageDocument.body.innerHTML = str;}

The above code var ev = ev || window.event ; uses one way or the other to complete the very perfect compatibility problem. In fact, in JavaScript there is a perfect way to deal with the compatibility of the problem is to use the if....else ... judgment, these two methods for me to deal with the compatibility problem provides a very good solution.

2. Event bubbling and cases

1. Event bubbling

Event bubbling very classic case, not much to say, on a piece of online very classic code directly look at the results, understand what is going on?

<script type="Text/javascript">Window.onload = function(){      //Gets the three element objects in a page      varObjDiv1 = document.getElementById (' Div1 ');varObjDiv2 = document.getElementById (' Div2 ');varObjDiv3 = document.getElementById (' Div3 ');//Event function to display the current ID       function func(){Alert This. ID); }//To three div binding an event function at the same timeObjdiv1.onclick = func;      Objdiv2.onclick = func;  Objdiv3.onclick = func; }</script><!--Three Div is physically involved in the relationship--<div id="Div1">    <div id="Div2">        <div id="Div3"></div>    </div></div>

Clicking DIV3 found a popup with three results, in fact binding only an event function to DIV3. This is the typical event bubbling. Some netizens said and Div's physical location, in fact, and the inclusion of the div between the relationship, and the physical location of the relationship does not have a semi-gross money relationship, do a test to know.

2. Cases that use event bubbling
The following case simulation is the implementation of the Web Sidebar sharing function, when the mouse moved to the Web sidebar sharing when a div can choose to share the list above the site, you can "share" into the sub-div using the event bubbling principle, the processing of the event to the parent div processing. This is easy to implement, the following code:

<style type="Text/css">   #box{width: + px;  height: + px;  position: absolute;  top: px; Left  : -px;  background: pink; }   #slider{ width: px ; Height: + px ; background: Grey ; position: Absolute ;Right  : -px ; top: px ; text-align: Center ; font-size: px ;}</style><script type="Text/javascript">window.onload =  function(){var objbox = document.getElementById (' box ')        );  //mouse-over event to parent div processing objbox.onmouseover =  function(){ ObjBox.style.left =       ' 0 '; } //mouse-out event to Parent div processing objbox.onmouseout =  function(){ obj       Box.style.left = ' -100px '; }   }       </script><!--Notice the structure of the page--<div id="box">  <div id="Slider">Click to share</div></div>
3. Understanding of the binding and capturing of events

1. What is Event binding?

This paragraph in the code above objDiv1.onclick = func ; is the event binding. Only this writing has limitations, for an object binding two events will be powerless, the following may cover the above.

function fn1(){   alert(this);   //alert(‘JavaScript‘);}function fn2(){   alert(‘jQuery‘);}//下面的事件绑定覆盖了上面的绑定事件document.onclick = fn1 ;document.onclick = fn2 ;

So there are two functions of the binding function of the event attachEvent()和addEventListener() , why are there two of them? Not much to say about the browser to deal with the two-camp browser binding event, so also to deal with compatibility issues, in dealing with compatibility issues, to figure out the difference between this two binding event function is the following code and analysis:

function  fn1   ()  { alert (this ); //alert (' JavaScript '); } function  fn2   { alert ( ' jQuery ' );} //non-standard IE bound event function  document.attachevent ( , fn1);d ocument.attachevent ( ' onclick ' , fn2); //The binding event function of the standard browser  document.addeventlistener ( ' click '           , Fn1,false ); Document.addeventlistener ( ' click ' , Fn2,false  );

Careful observation of the above results summarizes the following differences:

Non-standard IE attachevent (' event name ', ' event function ');
    • High-version IE execution-time positive sequence
    • The event name is preceded by an on
    • Event not captured
    • Called when this point is to the window (this pointer problem is often encountered)
Standard: AddEventListener (event name, event function, whether capture), where catch default is false: Bubble true: Capture
    • Event name not on
    • Positive sequence at event execution
    • Events to capture
      This time you can encapsulate a function that agrees to solve this compatibility problem as follows:
//eventobj represents the object to bind the event to, EventName binds the event name, Funname event function function bindevent(eventobj,eventname,funname){   //Standard browser    if(Eventobj.addeventlistener) {Eventobj.addeventlistener (Eventname,funname,false); }Else{//non-standard browserEventobj.attachevent (' on '+eventname, function(){            //fix this pointing problemFunname.call (EVENTOBJ);    }); }} function fn1(){Alert This);}//Call TestBindevent (document,' click ', FN1);

The call () function, which may be difficult to understand above, is the calling () function. Is the same as a normal call. In fact, call () is the method object below a method, the normal calling function is the function name plus parentheses can be called. Another method is the name of the function. Call (parameter one, parameter two, parameter three ...);

    • Parameter one indicates the object to which this method has been called after
    • Parameters after parameter two are incoming parameters of the function
function fn3(arg1,arg2){    alert(this);    alert(arg1 + arg2);}//document参数就是函数执行完毕要返回的对象,从第二个参数开始就是函数的参数了fn3.call(document,66,99);

2. Capture of events
There is a parameter in the function that binds the event above, and the parameter means whether or not to capture the meaning of the event, so how can event capture be understood?

Event bubbles out when set to False
When set to true inward capture event
One is when the event comes in. Trigger Event function
One is when the event goes out. Trigger Event function
The following code makes it easy to understand:

<script type="Text/javascript">Window.onload = function(){       varObjDiv1 = document.getElementById (' Div1 ');varObjDiv2 = document.getElementById (' Div2 ');varObjDiv3 = document.getElementById (' Div3 ');//Observation program execution orderObjdiv1.addeventlistener (' click ', function(){Alert3); },false); Objdiv2.addeventlistener (' click ', function(){Alert1); },true) Objdiv3.addeventlistener (' click ', function(){Alert2); },false); }</script><div id="Div1">   <div id="Div2">       <div id="Div3"></div>   </div></div>

Note The above code is analyzed.

4. Keyboard events

These events are often used in keyboard events:

onkeydown:当键盘按下的时候触发onkeyup:当键盘抬起的时候触发ev.keyCode:键盘按键的值,数字类型ctrlKey,altKey,shiftKey:返回布尔值

Examples of simulated chat rooms:

<script type="Text/javascript">Window.onload = function(){        varObjtext = document.getElementById (' txt ');varObjul = document.getElementById (' Ulone ');//Trigger when button is liftedObjtext.onkeyup = function(EV){            varEV = EV | | window.event;if( This. value! ="'){if(Ev.keycode = = -){varObjli = Document.createelement (' Li '); objli.innerhtml = This. value;if(objul.children[0]) {Objul.insertbefore (objli,objul.children[0]); }Else{Objul.appendchild (OBJLI); }//Clear the contents of the text box                     This. Value ="'; }            }        }    }</script><input type="text" id="txt"><ul id="Ulone"></ul>
5. Ways to block the default behavior of an event

Blocking the default behavior of the event, such as a common browser right-click Automatically pops up the browser itself's binding right-click event, sometimes the writer does not need these default events, but its own custom events, this time to prevent the default event can be used in the functionreturn false;

6. Dragging a case

It is often seen that a panel in a rich text frame can make the window larger and smaller, while dragging. What is the principle of drag? When the mouse click on the div when the onmousedown event occurs, the mouse button to move the mouse after the onmousemove event, drag to the destination after the mouse to lift the time of the OnMouseUp event occurs, this is the whole principle of drag.

varObjdiv = document.getElementById (' box '); Objdiv.onmousedown = function(EV){    //Get Event object    varEV = Window.event | | EV;//Calculate the distance from the div edge of the mouse click Point    varDISX = Ev.clientx-objdiv.offsetleft;varDisy = Ev.clienty-objdiv.offsettop; Document.onmousemove = function(EV){        varEV = Window.event | |        EV; ObjDiv.style.left = Ev.clientx-disx +' px '; ObjDiv.style.top = Ev.clienty-disy +' px '; } Document.onmouseup = function(){Document.onmousemove = Document.onmouseup =NULL; }}

Today the content is indeed a bit more, too tired, wash and sleep ...


Very happy to exchange study with everybody
Free reprint, creative license, please article source, from here
(Http://blog.csdn.net/unikylin)

Event review in JavaScript

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.