Home > Web Front-end > JS Tutorial > JavaScript DOM events (notes)_javascript skills

JavaScript DOM events (notes)_javascript skills

WBOY
Release: 2016-05-16 16:05:14
Original
993 people have browsed it

Chapter 1 Event Flow

1-1. Event bubbling: The event is initially received by the most specific element (the node with the deepest nesting level in the document);
Then propagate up to the least specific node (document) step by step;
1-2. Event capture: Less specific nodes should receive events earlier, while the most specific nodes should receive events last;

Chapter 2 Event Handler

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

<input type="button" value="按钮" onclick="showMessage()">
Copy after login

2-2 DOM level 0 event handler

//The more traditional way: assign a function to the handler attribute of an event, which is more commonly used;
//Advantages: Simple/cross-browser;

<input type="button" value="按钮" id="btn2">
<script>
  var btn2 = document.getElementById('btn2'); //取得btn2按钮对象;
  btn2.onclick = function () {        //给btn2添加onclick属性;
    alert('这是通过DOM0级添加的事件!');
  }
  btn2.onclick=null;             //删除onclick属性;
</script>
Copy after login

2-3 DOM2 level event handler

//DOM2 level events define two methods: for handling the operations of specifying and deleting event handlers;
//addEventListener() and removeEventListner();
//Receive three parameters: event name to be processed/event processing function and Boolean value;
//It doesn’t work in IE8;

<input type="button" value="按钮" id="btn3">
<script>
  var btn3 = document.getElementById('btn3');
  btn3.addEventListener('click',showMessage,false);    //添加事件程序;
  btn3.addEventListener('click',function(){        //添加多个事件程序;
    alert(this.value);
  },false);
  btn3.removeEventListener('click',showMessage,false);  //删除事件程序;
</script>
Copy after login

2-4 IE event handler and cross-browser

//Receives two parameters: event processing function name and event processing function

<script>
   var btn3 = document.getElementById('btn3');
   btn3.attachEvent('onclick',showMessage);      //添加事件;
   btn3.detachEvent('onclick',showMessage);      //删除事件;
</script>
Copy after login

>2. Browser compatible

//将添加和删除事件处理程序封装到对象中并赋值给变量'eventUtil';
var eventUtil = {
  //添加句柄
  addHandler:function(element,type,handler){
    //判断DOM2级事件处理程序;
    if(element.addEventListener){  
      element.addEventListener(type,handler,false);
    //判断IE浏览器;
    }else if(element.attachEvent){
      element.attachEvent("on"+type,handler);
    //使用DOM0级事件处理程序;
    }else{
      element['on'+type] = handler;
    }
  };
  //删除句柄
  removeHandler:function(element,type,handler){
    //判断DOM2级事件处理程序;
    if(element.removeEventListener){  
      element.removeEventListener(type,handler,false);
    //判断IE浏览器;
    }else if(element.detachEvent){
      element.detachEvent("on"+type,handler);
    //使用DOM0级事件处理程序;
    }else{
      element['on'+type] = null;
    };
  };
};
//跨浏览器添加事件处理程序;
eventUtil.addHandler(btn3,'click',showMessage);
Copy after login

Chapter 3 Event Object

3-1 Event objects in DOM

//When an event on the DOM is triggered, an object ==event will be generated;

>1.type == Get event type;
>2.target == Get event target;
>3.stopPropagation() == Stop event bubbling;
>4.preventDefault() == Default behavior of preventing events;

function showMes(event){
  alert(event.type);          //onclick;点击事件;
  alert(event.target.nodeName);    //INPUT;input按钮被触发;
  event.stopPropagation();      //停止事件冒泡;
}
<a href="event.html" onclick="stopGoto();">跳转</a>
function stopGoto(event){
  event.preventDefault();       //阻止默认行为;
}
Copy after login

3-2 Event objects in IE

>1.type == Same as above;
>2.srcElement attribute == Get event target;
>3.cancleBubble attribute == Prevent bubbling; set true to prevent bubbling, false to not prevent bubbling;
>4.returnValue attribute == Default behavior for blocking events;

function showMes(event){
  //非IE用event,IE8以下用window.event;
  event = event || window.event;  
  //事件目标兼容;
  var ele = event.target || event.srcElement;
  //兼容阻止事件冒泡;
  if(event.stopPropagation){
    event.stopPropagation();
  }else{
    event.cancleBubble();
  };
  //兼容取消事件默认行为;
  if(event.preventDefault){
    event.preventDefault();
  }else{
    event.returnValue = false;
  }
}
Copy after login

Chapter 4 QQ Panel Drag Effect

>1. Encapsulate the Class method

function getClass(clsName,parent){
  var oParent = parent&#63;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;
}
Copy after login

>2. Encapsulate drag and drop function

window.onload = drag;
function drag(){
  var oTitle = getClass('login_logo_webqq','loginPanel')[0];  
  //拖拽
  oTitle.onmousedown = fnDown;
  //关闭弹窗
  var oClose = document.getElementById('ui_boxyClose');
  oClose.onclick = function(){
    document.getElementById('loginPanel').style.display = 'none';
  }
  //切换状态
  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){
    //阻止冒泡到document使ul隐藏;
    e = e || window.event;
    if(e.stopPropagation){
      e.stopPropagation();
    }esle{
      e.cancleBubble = true;
    }
    stateList.style.display = "block";
  }
  //鼠标滑过/离开和点击状态列表时
  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){
      //阻止冒泡到loginState使stateList显示;
      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";
  }
}
//鼠标按下事件;
function fnDown(event){
  event = event || window.event;
  var oDrag = document.getElementById('loginPanel'),
      //鼠标按下时,鼠标和面板之间的距离;
      disX = event.clientX - oDrag.offsetLeft,
      disY = event.clientY - oDrag.offsetTop;
  //移动
  document.onmouseover = function(event){
    event = event || window.event;
    fnMove(event,disX,disY);
  }
  //释放鼠标
 document.onmouseup = function(){
  document.onmouseover = null;
  document.onmouseup = null;
  }
}
//鼠标移动事件;
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';
}
Copy after login

Chapter 4 Lottery System

>1.Keyboard events

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

>2. Lottery procedure

var data = ['iPhone5','iPad','三星电脑','谢谢参与'],
    timer = null,
    flag = 0;
window.onload = function(){
  var play = document.getElementById('play'),
    stop = document.getElementById('stop');
  //(鼠标)开始抽奖
  play.onclick = palyFun;
  stop.onclick = stopFun;
  //(键盘Enter)开始抽奖
  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');
  //清除之前的定时器,放置定时器重复;
  clearInterval(timer);
    //设置定时器;
  timer = setInterval(function(){
    //随机数*数组元素个数=数组随机索引;
    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';  
}
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template