JavaScript DOM Events (notes) _javascript tips

Source: Internet
Author: User

1th Chapter Event Flow

1-1. Event bubbling: The event was first received by the most specific element (the node with the deepest nesting level in the document);
It then propagates up to the least specific node (document);
1-2. Event capture: Less specific nodes should receive the event earlier, and the most specific node receives the event at the end;

2nd Chapter Event Handling procedure

2-1 an HTML event handler
Disadvantages: HTML and JS code tightly coupled together;

<input type= "button" value= "buttons" onclick= "ShowMessage ()" >

2-2 DOM0 Level Event handler

More traditional way: To assign a function to an event handler properties, with more;
Advantages: Simple/cross-browser;

<input type= "button" value= "buttons" id= "btn2" >
<script>
  var btn2 = document.getElementById (' btn2 '); /Get Btn2 button object;
  Btn2.onclick = function () {        //To add onclick property to Btn2;
    Alert (' This is an event added through the DOM0 level! ');
  }
  Btn2.onclick=null;             Deletes the onclick attribute;
</script>

2-3 DOM2 Level Event handler

The DOM2 level event defines two methods that are used to handle the operation of specifying and deleting an event handler;
AddEventListener () and Removeeventlistner ();
Receive three parameters: event name/Event handler and Boolean value to be processed;
In IE8, it does not work;

<input type= "button" value= "buttons" id= "Btn3" >
<script>
  var btn3 = document.getElementById (' btn3 ');
  Btn3.addeventlistener (' click ', Showmessage,false);    Add event program;
  Btn3.addeventlistener (' click ', Function () {        //Add multiple event programs;
    alert (this.value);
  },false);
  Btn3.removeeventlistener (' click ', Showmessage,false);  Delete event program;
</script>

2-4 IE event handlers and Cross-browser

Two parameters Received: event handler function name and event handler function

<script>
   var btn3 = document.getElementById (' btn3 ');
   Btn3.attachevent (' onclick ', showmessage);      Add an event;
   Btn3.detachevent (' onclick ', showmessage);      Deletes an event;
</script>

>2. Browser compatible

Encapsulates the Add and remove event handlers into an object and assigns a value to the variable ' eventutil ';
var eventutil = {/
  /Add handle
  addhandler:function (element,type,handler) {
    //Judge DOM2 level event handler;
    if (element.addeventlistener) {  
      element.addeventlistener (type,handler,false);
    Judge IE browser;
    } else if (element.attachevent) {
      element.attachevent ("on" +type,handler);
    Use the DOM0 level event handler;
    else{
      element[' on ' +type] = handler;
    }
  ;
  Delete handle
  removehandler:function (element,type,handler) {
    //Judge DOM2 level event handler;
    if (element.removeeventlistener) {  
      element.removeeventlistener (type,handler,false);
    Judge IE browser;
    } else if (element.detachevent) {
      element.detachevent ("on" +type,handler);
    Use the DOM0 level event handler;
    else{
      element[' on ' +type] = null;
    }
;}; Add an event handler across browsers;
Eventutil.addhandler (btn3, ' click ', ShowMessage);

Chapter 3rd Event Objects

Event objects in the 3-1 DOM

An object ==event is generated when the event on the DOM is triggered;

>1.type = = Get event type;
>2.target = = Get the event target;
>3.stoppropagation () = = Stop event bubbling;
>4.preventdefault () = = Block The default behavior of an event;

function Showmes (event) {
  alert (event.type);          onclick; Click the event;
  alert (event.target.nodeName);  The Input;input button is triggered;
  Event.stoppropagation ();      Stop event bubbling;
<a href= "event.html" onclick= "Stopgoto ();"       > Jump </a>
function Stopgoto (event) {
  event.preventdefault (); Block default behavior;

3-2 the event object in IE

>1.type = = ditto;
>2.srcelement attribute = = Get event target;
>3.canclebubble Property = = Block bubbling; set true to prevent bubbling, false to not organize bubbles;
>4.returnvalue Property = = is used to block the default behavior of events;

function Showmes (event) {
  //non ie used event,ie8 below with window.event;
  Event = Event | | window.event;  
  The event target is compatible;
  var ele = Event.target | | event.srcelement;
  Compatible block event bubbling;
  if (event.stoppropagation) {
    event.stoppropagation ();
  } else{
    event.canclebubble ();
  };
  Compatible cancellation event default behavior;
  if (event.preventdefault) {
    event.preventdefault ();
  } else{
    event.returnvalue = false;
  }
}

4th Chapter QQ Panel drag and drop effect

>1. Encapsulation Fetch class method

function GetClass (clsname,parent) {
  var oparent = Parent?document.getelementbyid (parent):d ocument,
      eles = [ ],
      elements = oparent.getelementsbytagname (' * ');

  for (var i=0,l=elements.length i<l; i++) {
    if (elements[i].classname = = clsname) {
      eles.push (Elements[i]) ;
    }
  }
  return eles;
}

>2. Package Drag function

Window.onload = drag;  
  function drag () {var otitle = getclass (' login_logo_webqq ', ' Loginpanel ') [0];
  Drag otitle.onmousedown = Fndown;
  Close the Pinball window var oclose = document.getElementById (' Ui_boxyclose ');
  Oclose.onclick = function () {document.getElementById (' Loginpanel '). style.display = ' None '; //Toggle state var loginstate = document.getElementById (' loginstate '), statelist = document.getElementById (' LoginStatePa Nel '), lis = statelist.getelementsbytagname (' li '), statetxt = document.getElementById (' Login2qq_state_txt '), L
  Oginstateshow = document.getElementById (' login-state_show ');
    Loginstate.onclick = function (e) {//block bubbling to document to make UL hide; E = e | |
    window.event;
    if (e.stoppropagation) {e.stoppropagation ();
    }esle{e.canclebubble = true;
  } stateList.style.display = "block";  ///mouse over/left and click Status list for (Var i=0,i<lis.length,i++) {lis[i].onmouseover = function () {This.style.background
    = "#567"; } lis[i].onmouseout = function () {this.style.background = "#fff";
      } Lis[i].onclick = function (e) {//block bubbling to loginstate to make statelist display; E = e | |
      window.event;
      if (e.stoppropagation) {e.stoppropagation ();
      }esle{e.canclebubble = true;
      var id = this.id;
      StateList.style.display = "None";
      statetxt.innerhtml = getclass (' stateselect_text ', id) [0].innerhtml;
      Loginstateshow.classname = ';
    Loginstateshow.classname = ' login-state-show ' +id;
  } Document.onclick = function () {StateList.style.display = ' none ';
}//Mouse down event;
  function Fndown (event) {event = event | | window.event;
      var Odrag = document.getElementById (' Loginpanel '),//the distance between mouse and panel when mouse is pressed;
  DISX = event.clientx-odrag.offsetleft, Disy = event.clienty-odrag.offsettop;
    Move Document.onmouseover = function (event) {event = event | | window.event;
  Fnmove (Event,disx,disy); //release Mouse document.onmouseup = function () {DOCUMENT.ONMOuseover = null;
  Document.onmouseup = null;
}//mouse movement events; function Fnmove (e,posx,posy) {var Odrag = document.getElementById (' Loginpanel '), L = e.clientx-posx, t = e. Clienty-posy, winw = Document.documentElement.clientWidth | | Document.body.clientWidth, Winh = Document.documentElement.clientHeight | |
   Document.body.clientHeight;
 Maxw = winw-odrag.offsetwidth, maxh = winh-odrag.offsetheight;
 if (l<0) {L = 0;
 }else if (L&GT;MAXW) {L = Maxw;
 } if (t<0) {t = 0;
 }else if (t>maxh) {t=maxh;
  } oDrag.style.left = l+ ' px ';
ODrag.style.top = t+ ' px '; }

4th Chapter Lottery System

>1. Keyboard events

>>1.keydown: Triggers when the user presses any key on the keyboard, and if pressed or not, the event is repeated;
>>2.keypress: Triggers when the user presses the word keys on the keyboard and, if pressed, repeats the event;
>>3.keyup: Triggers when the user releases a key on the keyboard;

>2. Lottery procedure

var data = [' IPhone5 ', ' IPad ', ' Samsung computer ', ' Thank you for participating '], timer = NULL, flag = 0;
  Window.onload = function () {var play = document.getElementById (' play '), stop = document.getElementById (' Stop ');
  (mouse) Start the lottery play.onclick = Palyfun;
  Stop.onclick = Stopfun; 
    (keyboard Enter) Start the lottery document.onkeyup = function (event) {event = event | | window.event;
        if (Event.keycode = = {if (flag = = 0) {palyfun ();
      flag = 1;
        }else{Stopfun ();
      Flag = 0; }} function Palyfun () {var title = document.getElementById (' title '), play = document.getElementById (' Play
  ');
  Clear the timer before, place the timer repeat;
    Clearinterval (timer);
  Set timer;
    Timer = setinterval (function () {//random number * Array element number = array random index;
    var random = Math.floor (Math.random () *data.length);
  title.innerhtml = Data[random];
  },50);
Play.style.background = "#999";
  function Stopfun () {clearinterval (timer);
  var paly = document.getElementById (' play '); Paly.style.background = ' #036 ';  
} 

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.