JavaScript DOM event of notes

  • 2020-05-27 04:13:25
  • OfStack

Chapter 1 flow of events

1-1. Event bubbling: the event is initially received by the most specific element (the node with the deepest nesting level in the document);
It then propagates up the hierarchy to the least concrete node (the document);
1-2. Event capture: the less specific node should receive the event earlier, while the most specific node will receive the event at last;

Chapter 2 event handlers

2-1 HTML event handler
// disadvantages :HTML and JS code are tightly coupled in 1;


<input type="button" value=" button " onclick="showMessage()">

2-2 DOM level 0 event handler

// the more traditional approach is to assign a function to an event handler property.
// pros: simple/cross-browser;


<input type="button" value=" button " id="btn2">
<script>
  var btn2 = document.getElementById('btn2'); // achieve btn2 The button object ;
  btn2.onclick = function () {        // to btn2 add onclick attribute ;
    alert(' This is done by DOM0 level !');
  }
  btn2.onclick=null;             // delete onclick attribute ;
</script>

2-3 DOM level 2 event handlers

//DOM2 level events define two methods: to handle the operation of specifying and deleting event handlers;
/ / addEventListener () and removeEventListner ();
/ / receive 3 parameters: event name to be processed/event handler function and Boolean value;
// under IE81, it does not work;


<input type="button" value=" button " id="btn3">
<script>
  var btn3 = document.getElementById('btn3');
  btn3.addEventListener('click',showMessage,false);    // Add event routine ;
  btn3.addEventListener('click',function(){        // Add multiple event programs ;
    alert(this.value);
  },false);
  btn3.removeEventListener('click',showMessage,false);  // Delete event routine ;
</script>

2-4 IE event handler and cross-browser

// receives two parameters: the name of the event handler and the event handler


<script>
   var btn3 = document.getElementById('btn3');
   btn3.attachEvent('onclick',showMessage);      // Add event ;
   btn3.detachEvent('onclick',showMessage);      // Delete events ;
</script>

> 2. Browser compatibility


// Encapsulate add and remove event handlers into objects and assign values to variables 'eventUtil';
var eventUtil = {
  // To add a handle 
  addHandler:function(element,type,handler){
    // judge DOM2 Level event handlers ;
    if(element.addEventListener){  
      element.addEventListener(type,handler,false);
    // judge IE The browser ;
    }else if(element.attachEvent){
      element.attachEvent("on"+type,handler);
    // use DOM0 Level event handlers ;
    }else{
      element['on'+type] = handler;
    }
  };
  // Remove the handle 
  removeHandler:function(element,type,handler){
    // judge DOM2 Level event handlers ;
    if(element.removeEventListener){  
      element.removeEventListener(type,handler,false);
    // judge IE The browser ;
    }else if(element.detachEvent){
      element.detachEvent("on"+type,handler);
    // use DOM0 Level event handlers ;
    }else{
      element['on'+type] = null;
    };
  };
};
// Add event handlers across browsers ;
eventUtil.addHandler(btn3,'click',showMessage);

Chapter 3 event objects

3-1 event objects in DOM

// when an event on DOM is triggered, 1 object is generated ==event;

> 1.type == get the event type;
> 2.target == get the event target;
> 3.stopPropagation() == stop event bubbling;
> 4.preventDefault() == default behavior for blocking events;


function showMes(event){
  alert(event.type);          //onclick; Click on the event ;
  alert(event.target.nodeName);    //INPUT;input The button is triggered ;
  event.stopPropagation();      // Stop the event bubbling ;
}
<a href="event.html" onclick="stopGoto();"> jump </a>
function stopGoto(event){
  event.preventDefault();       // Blocking default behavior ;
}

Event objects in 3-2 IE

> 1.type == ibid.
> 2.srcElement property == get the event target;
> 3.cancleBubble property == prevent bubbling; Set true to prevent bubbling,false to prevent bubbling;
> 4.returnValue property == the default behavior used to prevent events;


function showMes(event){
  // non IE with event,IE8 The following use window.event;
  event = event || window.event;  
  // Event target compatibility ;
  var ele = event.target || event.srcElement;
  // Compatibility prevents event bubbling ;
  if(event.stopPropagation){
    event.stopPropagation();
  }else{
    event.cancleBubble();
  };
  // Compatible with the default behavior of the cancel event ;
  if(event.preventDefault){
    event.preventDefault();
  }else{
    event.returnValue = false;
  }
}

Chapter 4 QQ panel drag effect

> 1. Encapsulate to get the Class method


function getClass(clsName,parent){
  var oParent = parent?document.getElementById(parent):document,
      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. Encapsulate drag and drop functions


window.onload = drag;
function drag(){
  var oTitle = getClass('login_logo_webqq','loginPanel')[0];  
  // Drag and drop 
  oTitle.onmousedown = fnDown;
  // Close Windows 
  var oClose = document.getElementById('ui_boxyClose');
  oClose.onclick = function(){
    document.getElementById('loginPanel').style.display = 'none';
  }
  // Switch state 
  var loginState = document.getElementById('loginstate'),
    stateList = document.getElementById('loginStatePanel'),
    lis = stateList.getElementsByTagName('li'),
    stateTxt = document.getElementById('login2qq_state_txt'),
    loginStateShow = document.getElementById('login-state_show');
  loginState.onclick = function(e){
    // Stop the bubbling document make ul hidden ;
    e = e || window.event;
    if(e.stopPropagation){
      e.stopPropagation();
    }esle{
      e.cancleBubble = true;
    }
    stateList.style.display = "block";
  }
  // The mouse slip / Leave and click on the 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){
      // Stop the bubbling loginState make stateList According to ;
      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'),
      // When the mouse is pressed down , The distance between the mouse and the panel ;
      disX = event.clientX - oDrag.offsetLeft,
      disY = event.clientY - oDrag.offsetTop;
  // mobile 
  document.onmouseover = function(event){
    event = event || window.event;
    fnMove(event,disX,disY);
  }
  // Release the mouse 
 document.onmouseup = function(){
  document.onmouseover = null;
  document.onmouseup = null;
  }
}
// Mouse movement event ;
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>maxW){
   l = maxW;
 }
 if(t<0){
   t = 0;
 }else if(t>maxH){
   t=maxH;
 }
  oDrag.style.left = l+'px';
  oDrag.style.top = t+'px';
}

Chapter 4 lottery system

> 1. Keyboard events

> > 1.keyDown: triggered when the user presses any key on the keyboard, and this event will be triggered repeatedly if the key is held.
> > 2.keyPress: triggered when the user presses a character key on the keyboard, and this event will be triggered repeatedly if the key is held.
> > 3.keyUp: triggered when the user releases the key on the keyboard;

> 2. Lottery procedures


var data = ['iPhone5','iPad','3 Star computer ',' Thank you for your participation '],
    timer = null,
    flag = 0;
window.onload = function(){
  var play = document.getElementById('play'),
    stop = document.getElementById('stop');
  //( The mouse ) Began to draw 
  play.onclick = palyFun;
  stop.onclick = stopFun;
  //( The keyboard Enter) Began to draw 
  document.onkeyup = function(event){
    event = event || window.event; 
    if(event.keyCode == 13){
      if(flag == 0){
        palyFun();
        flag = 1;
      }else{
        stopFun();
        flag = 0;
      }
    }
  }
}
function palyFun(){
  var title = document.getElementById('title'),
    play = document.getElementById('play');
  // Clear the previous timer , Place the timer repeat ;
  clearInterval(timer);
    // Set timer ;
  timer = setInterval(function(){
    // The random number * Number of array elements = 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';  
}

Related articles: