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

JavaScript DOM events (notes)_javascript skills

May 16, 2016 pm 04:05 PM
dom javascript

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
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles