Home Web Front-end JS Tutorial JavaScript Event Learning Chapter 7 Event Properties_Javascript Skills

JavaScript Event Learning Chapter 7 Event Properties_Javascript Skills

May 16, 2016 pm 06:35 PM
event

When we want to read some information about Event, we are often buried in a large number of attributes, most of which do not run well in most browsers. Here is the event compatibility list.
I am not going to make a list of these attributes, because those situations are too confusing, and it will not be helpful to your learning at all. Before writing the 5 pieces of code, I want to ask 5 questions about the browser.
1. What is the type of event?
2. Which HTML element is the target of the event?
3. Which keys were pressed when the event occurred?
4. Which mouse button was pressed when the Event occurred?
5. Where is the mouse position when the Event occurs?
I have given a very detailed answer to the last question here.
Please note that I have done very strict object checking on these codes. I first created cross-browser access to the event, and then checked for browser support before using each attribute.

1. What is the type of event?
This is a cross-browser question with a standard answer: Use the type attribute to view its properties:

Copy code The code is as follows:

function doSomething(e) {
if (!e) var e = window.event;
alert(e.type);
}



2. Which HTML element is the target of the event?
W3C/Netscape said: target. No, Microsoft said, it's srcElement. Both properties return the HTML element when the event occurred.
Copy code The code is as follows:

function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}


The last two lines of code are specifically for Safari. If an event occurs on an element that contains text, the text node becomes the target of the event rather than the element itself. So we want to check if the target's nodetype is 3 (text node). If it is, we move it to the parent node, the HTML element.
Even if the event is captured or bubbles up (bubbles up), the target/srcElement attribute is still the element where the event occurred earliest.
Other targets
There are many targeting attributes. I discussed currentTarget in the article Event Order and relatedTarget, fromElement and toElement in the article Mouse event.


3. Which keys were pressed when the event occurred?
This question is relatively simple. First get the code of the key (a=65) from the keyCode attribute. After you get the key value, you can know the actual key value through the String.fromCharCode() method, if necessary.
Copy code The code is as follows:

function doSomething(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert('Character was ' character);
}


There are some places here that may make keyboard events difficult to use. For example, the kepress event fires as long as the user presses the key. However, the triggering time of keydown in most browsers is as long as the pressing time. I'm not sure if that's a good idea, but that's what it is.


4. Which mouse button was pressed when the Event occurred?
There are two properties here to know which mouse button was pressed: which and button. Please note that these properties generally do not necessarily work on click. To safely detect which mouse button was pressed, you'd better use the mousedown and mouseup events.
which is an old Netscape property. The value of the left mouse button is 1, the value of the middle button (scroll wheel) is 2, and the value of the right mouse button is 3. There are no problems except for the weak support. In fact, it is often used to detect mouse buttons.
Button attributes are now well recognized. W3C's standard values ​​are as follows:
Left button 0
Middle button 1
Right button 2
Microsoft's standard values ​​are as follows:
Left button 1
Middle button 4
Right button 2
There is no doubt that Microsoft’s standards are better than W3C’s. 0 can mean that no key is pressed, and everything else is unreasonable.
In addition, only in the Microsoft model, the values ​​of the buttons can be combined. For example, 5 means that the "left button and middle button" are pressed together. Not only does IE6 not support merging, but the w3c model is theoretically impossible: you never know whether the left button was pressed.
So in my opinion w3c has made a serious mistake in defining buttons.

Right Click
Fortunately, usually you want to know if the right button was clicked. Because W3C and Microsoft happen to define the button value as 2 on this issue, you can still detect right clicks.
Copy code The code is as follows:

function doSomething(e) {
var rightclick;
if (!e) var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e. button == 2);
alert('Rightclick: ' rightclick); // true or false
}


It should be noted that Macs usually only have one button, Mozilla defines the value of the Ctrl-Click button as 2, so Ctrl-Click will also open the menu. ICab does not yet support mouse button attributes, so you cannot detect right clicks in Opera.
5. Where is the mouse position when the Event occurs?
The problem of mouse position is quite serious. Although there are no less than 6 properties for mouse coordinates, there is still no reliable cross-browser method to find the mouse coordinates.
The following are these 6 sets of coordinates:
1. clientX, clientY
2. layerX, layerY
3. offsetX, offsetY
4. pageX, pageY
5. screenX, screenY
6. x, y
I once explained the issues of pageX/Y and clientX/Y here.
screenX and screenY are the only pair of properties that are cross-browser compatible. They give the coordinates of the mouse across the entire computer screen. Unfortunately, this information alone is not enough: you never need to know where the mouse is on the screen - well, maybe you want to place a new window at the current mouse position.
The other three pairs of attributes are not important, see the description here.
Correct code
The following code can correctly detect the coordinates of the mouse
Copy the code The code is as follows:

function doSomething(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e .pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX document.body.scrollLeft
document.documentElement.scrollLeft;
posy = e.clientY document.body.scrollTop
document.documentElement.scrollTop;
}
// posx and posy contain the mouse position relative to the document
// Do something with this information
}


Original text here: http://www.quirksmode.org /js/events_properties.html

Please give me some advice on my twitter: @rehawk
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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

10 Ways to Instantly Increase Your jQuery Performance 10 Ways to Instantly Increase Your jQuery Performance Mar 11, 2025 am 12:15 AM

This article outlines ten simple steps to significantly boost your script's performance. These techniques are straightforward and applicable to all skill levels. Stay Updated: Utilize a package manager like NPM with a bundler such as Vite to ensure

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Using Passport With Sequelize and MySQL Using Passport With Sequelize and MySQL Mar 11, 2025 am 11:04 AM

Sequelize is a promise-based Node.js ORM. It can be used with PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. In this tutorial, we will be implementing authentication for users of a web app. And we will use Passport, the popular authentication middlew

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

See all articles