Home Web Front-end JS Tutorial JavaScript事件 "事件对象"的注意要点_javascript技巧

JavaScript事件 "事件对象"的注意要点_javascript技巧

May 16, 2016 pm 03:20 PM
javascript event object

在触发DOM上的某个事件时,会产生一个事件对象event。

DOM中的事件对象

兼容DOM的浏览器会将一个event对象传入到事件处理程序中。event对象包含与创建它的特定事件有关的属性和方法。除法的事件类型不一样,可用的属性方法就不一样。不过,所有的事件都会有下表列出的成员。

下面列出了 2 级 DOM 事件标准定义的属性:

  • bubbles: 返回布尔值,指示事件是否是起泡事件类型。
  • cancelable: 返回布尔值,指示事件是否可拥可取消的默认动作。
  • currentTarget: 返回其事件监听器触发该事件的元素。
  • eventPhase: 返回事件传播的当前阶段。
  • target: 返回触发此事件的元素(事件的目标节点)。
  • timeStamp: 返回事件生成的日期和时间。
  • type: 返回当前 Event 对象表示的事件的名称。

下面列出了 2 级 DOM 事件标准定义的方法。IE 的事件模型不支持这些方法:

  • initEvent(): 初始化新创建的 Event 对象的属性。
  • preventDefault(): 通知浏览器不要执行与事件关联的默认动作。
  • stopPropagation(): 不再派发事件。

this、target、currentTarget

在事件处理程序的内部,对象this始终等于currentTarget的值,而target则只包含事件的实际目标。如果直接将事件处理程序指定给了目标元素,则this、currentTarget和target包含相同的值。如:

var btn = document.querySelector("#btn");
btn.onclick=function () {
 console.log(event.currentTarget === this); //true
 console.log(event.target === this); //true
}
Copy after login

由于click事件的目标是btn按钮,所以这三个值是相等的。如果事件处理程序在按钮的父节点(document.body)中,那么这些值则不相同。如:

var btn = document.querySelector("#btn");
document.body.onclick=function () {
 console.log(event.currentTarget === document.body); //true
 console.log(this === document.body); //true
 console.log(event.target === btn); //true 因为btn没有注册事件处理程序,所以该click事件就冒泡到了document.body
}
Copy after login

在这里,this和currentTarget都是document.body,因为事件处理程序是注册到这个元素上的。但是target元素却等于按钮元素,因为它是click事件的真正目标。由于按钮并没有注册事件处理程序,结果click事件就冒泡到了document.body,在那里事件才能得到处理。

type

在需要通过一个函数处理多个事件时,可以使用type属性。如:

//获取按钮
var btn = document.querySelector("#btn");
//设置多个事件
var handler = function() {
//检测事件的类型
 switch (event.type) {
  case "click":
   console.log("i click it");
   break;
  case "mouseover":
   console.log("i enter it");
   break;
  case "mouseout":
   console.log("i leave it");
   break;
 }
}
//给响应的事件赋值
btn.onclick = handler;
btn.onmouseover = handler;
btn.onmouseout = handler;
preventDefault()

Copy after login

要阻止特定事件的默认行为,可以使用该方法。如:

var aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
 var currentATag = aTags[i];
 currentATag.onclick = function() {
  event.preventDefault();
 }
};
Copy after login

以上代码即屏蔽了网页上全部的a标签超链接功能。要注意的是,只有cancelable属性设置为true的事件,才可以使用preventDefault()来取消其默认行为。

stopPropagation()

立即停止事件在DOM层次中的传播,即取消进一步的事件捕获或冒泡。例如,直接添加到一个按钮的事件处理程序可以调用该方法,从而避免触发注册在document.body上面的事件处理程序。如:

var btn = document.getElementById("btn");
btn.onclick = function () {
 console.log("btn clicked");
 // event.stopPropagation();
};
window.onclick = function () {
 console.log("clicked");
};
//单击一下的结果:
//btn clicked
//clicked
Copy after login

又如:

var btn = document.getElementById("btn");
btn.onclick = function () {
 console.log("btn clicked");
 event.stopPropagation();
};
window.onclick = function () {
 console.log("clicked");
};
//单击一下的结果:
//btn clicked
Copy after login

eventPhase

该属性用来确定事件当前正位于事件流的哪个阶段。

1、如果是捕获阶段则等于1;
2、如果是目标对象阶段则等于2;
3、如果是冒泡阶段则等于3;
如:

var btn = document.getElementById("btn");

document.body.addEventListener("click", function() {
 console.log("bodyListener" + event.eventPhase);
}, true) //捕获阶段

btn.onclick = function() {
 console.log("btn" + event.eventPhase);
} //目标对象阶段,实际上属于冒泡阶段(在btn上)

document.body.onclick = function() {
 console.log("body" + event.eventPhase);
} //冒泡阶段(在body上)

Copy after login

又如:

var btn = document.getElementById("btn");

document.body.addEventListener("click", function() {
 console.log(event.eventPhase); //1
 console.log(event.currentTarget); //HTMLBodyElement
}, true);

btn.addEventListener("click", function() {
 console.log(event.eventPhase); //2
 console.log(event.currentTarget); //HTMLInputElement
});

document.body.addEventListener("click", function() {
 console.log(event.eventPhase); //3
 console.log(event.currentTarget); //HTMLBodyElement
});

Copy after login

流程大概是:

document.body 捕获阶段 --> btn 目标对象阶段 --> document.body 冒泡阶段

以上就是本文的全部内容,希望对大家的学习有所帮助。

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

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

What is the difference between arrays and objects in PHP? What is the difference between arrays and objects in PHP? Apr 29, 2024 pm 02:39 PM

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values ​​are passed and object references are passed.

How to implement change event binding of select elements in jQuery How to implement change event binding of select elements in jQuery Feb 23, 2024 pm 01:12 PM

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

What is the Request object in PHP? What is the Request object in PHP? Feb 27, 2024 pm 09:06 PM

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

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

See all articles