当前位置:网站首页>JS event details
JS event details
2022-06-24 18:35:00 【Brother Mengfan】
Catalog
1.1、 Traditional way of registration
1.2、 Monitor registration method
1.3、 Comparison of two registration methods
5.1 The objective of the event
6.1、 Stop the event from bubbling
6.2、 Blocking default behavior
6.2.1、 Block the default behavior of links
6.2.2、 Prevent the submit button from submitting the default behavior of the form
One 、 Event registration
1.1、 Traditional way of registration
<button onclick="console.log('haha, Cheat you. ...')"> I have a prize </button>(2) adopt DOM Object to the specified properties
<button id="btn"> Am I ..</button>
<script>
var btn = document.querySelector('#btn');
btn.onclick = function() {
console.log(' thank you ....')
};
</script>1.2、 Monitor registration method
Another way to register special events is to register through event listening , It's called setting up event listeners , It is W3C The standard recommends the use of . adopt EventTarget.addEventListener() Method to implement .
target.addEventListener(type, listener, useCapture); <button> Click on </button>
<script>
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
console.log(' Good weekend, everyone !');
});
</script>1.3、 Comparison of two registration methods
(1) If you register in the traditional way , When adding the same event to the same object , Later events will overwrite the previous events ; If you register by listening , When the same object is bound to the same multiple events , These events will be executed .
(2) The traditional registration method can only bubble , Cannot capture ; The monitoring registration method can bubble or capture .
Example :
<button class="btn1"> Traditional registration </button>
<button class="btn2"> Monitor registration </button>
<script>
var btn1 = document.querySelector('.btn1');
var btn2 = document.querySelector('.btn2');
// Traditional registration
btn1.onclick = function () {
console.log(' Tomorrow Monday , Let's have a rest , You can sleep in , ha-ha ');
};
btn1.onclick = function () {
console.log(' On Tuesday we continue ');
};
// Monitor registration
btn2.addEventListener('click', function () {
console.log(' Today is Sunday , Class is almost over , ha-ha ');
});
btn2.addEventListener('click', function () {
console.log(' But it will take time to digest today's content .');
});
</script>Two 、 Unbind event
eventTarget. Event type = null;eventTarget.removeEventListener(type, listener[, useCapture]);<button class="btn1"> Traditional registration </button>
<button class="btn2"> Monitor registration </button>
<script>
var btn1 = document.querySelector('.btn1');
var btn2 = document.querySelector('.btn2');
// Traditional registration
btn1.onclick = function() {
console.log(' Tomorrow Monday , Let's have a rest , You can sleep in , ha-ha ');
};
// Unbind event
btn1.onclick = null;
// Monitor registration
/* Cannot unbind the event
btn2.addEventListener('click', function () {
console.log(' Today is Sunday , Class is almost over , ha-ha ');
});
btn2.removeEventListener('click', function () {
console.log(' We have nothing to do .')
});*/
function fn() {
console.log(' Today is Sunday , Class is almost over , ha-ha ');
btn2.removeEventListener('click', fn);
}
btn2.addEventListener('click', fn);
</script>Be careful :
about Traditional registration Events The unbundling of :
(1) Write the unbinding event anywhere in the function , Its registration event will be executed only once ;
(2) Write the unbinding event before the registration event outside the function , Unbind event is invalid for it ; Write the unbinding event after the registration event outside the function , Registration events will not be executed .
about Listen for registration events The unbundling of :
(1) Write the unbinding event anywhere in the function , Its registration event will be executed only once ;
(2) take The unbinding event is written outside the function , Then the registered event will be invalid .
(3) Unbind the listening registration method , Note that the event type and listener function must be the same , Otherwise, unbinding is invalid .
3、 ... and 、 Flow of events
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Flow of events </title>
<style>
.outer {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: blueviolet;
text-align: center;
}
.inner {
width: 200px;
height: 200px;
margin: 50px;
background-color: cornflowerblue;
line-height: 200px;
color: #fff;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"> Inner box </div>
</div>
<script>
var inner = document.querySelector('.inner');
var outer = document.querySelector('.outer');
inner.addEventListener('click', function () {
console.log('inner');
});
outer.addEventListener('click', function () {
console.log('outer');
});
// to body Add click event
document.body.addEventListener('click', function () {
console.log('body');
});
// to html Add click event
document.documentElement.addEventListener('click', function () {
console.log('html');
});
// to document Add click event
document.addEventListener('click', function () {
console.log('document');
});
window.addEventListener('click', function () {
console.log('window');
});
</script>
</body>
</html>

Be careful :
(1)JavaScript Only one of the capture or bubbling phases can be performed in the code , Or bubbling , Or capture .
(2)onclick And attachEvent Only the bubbling stage is available for registered events .
(3)addEventListener(type, listener[, useCapture]) The third parameter is zero true Represents the capture phase , The default is empty or false It's the bubbling stage .
3.1、 Event Bubbling
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Event Bubbling </title>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box')
box.addEventListener('click', function () {
console.log("div")
});
document.body.addEventListener('click', function () {
console.log('body');
});
document.documentElement.addEventListener('click', function () {
console.log('html');
});
</script>
</body>
</html>Running results :

Be careful : Event bubbling is the upward propagation from the target object .
3.2、 Event capture
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Event capture </title>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box')
box.addEventListener('click', function() {
console.log("div")
}, true);
document.body.addEventListener('click', function() {
console.log('body');
}, true);
document.documentElement.addEventListener('click', function() {
console.log('html');
}, true);
</script>
</body>
</html>Running results :

Four 、 Event object
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Event object </title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
</ul>
<script>
var ul = document.querySelector('ul');
ul.addEventListener('click', function(event) {
// Dealing with compatibility issues
event = event || window.event;
console.log(event);
// From the event object event Get the target object in
console.log(event.target.innerHTML);
});
</script>
</body>
</html>5、 ... and 、 Event properties

Example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Event object properties </title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #ff6700;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box')
box.onclick = function (event) {
event = event || window.event;
// 1. Get target object
// 1.1 target standard
console.log(event.target)
// 1.2 srcElement Nonstandard
console.log(event.srcElement);
// 2. Get event type , No on
console.log(event.type);
// 3. Get the coordinates in the visualization area
console.log(event.clientX + ', ' + event.clientY);
};
</script>
</body>
</html>5.1 The objective of the event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Event object target </title>
<style>
ul,li {
list-style: none;
}
.item {
width: 100px;
height: 50px;
background-color: #ff6700;
margin: 10px;
text-align: center;
line-height: 50px;
color: white;
}
</style>
</head>
<body>
<ul id="box">
<li class="item">1</li>
<li class="item">2</li>
</ul>
<script>
var box = document.querySelector('#box')
box.onclick = function (event) {
event = event || window.event;
console.log(event.target);
console.log(event.srcElement);
console.log(event.currentTarget);
console.log(this);
};
</script>
</body>
</html>explain :
(1)currentTarget: What is returned is the object that binds the event ;
(2)target: What is returned is the actual target object of the event (IE8 I won't support it );
5.2、 Event delegation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Event delegation </title>
<style>
* {
padding: 0;
margin: 0;
}
ul {
list-style: none;
overflow: hidden;
margin-top: 80px;
}
ul li {
float: left;
width: 100px;
height: 30px;
text-align: center;
line-height: 30px;
color: #fff;
background-color: #000;
margin: 0 10px
}
</style>
</head>
<body>
<ul id="box">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
var ul = document.querySelector('#box')
/*
var lis = document.querySelectorAll('li')
for (var i = 0; i < lis.length; i++) {
lis[i].onmouseover = function () {
this.style.backgroundColor = 'blue';
};
lis[i].onmouseout = function () {
this.style.backgroundColor = 'black';
};
}*/
// Use event delegation
ul.onmouseover = function(e) {
console.log(e);
if (e.target.nodeName.toLowerCase() === 'li') {
e.target.style.backgroundColor = 'blue';
}
};
ul.onmouseout = function(e) {
if (e.target.nodeName.toLowerCase() === 'li') {
e.target.style.backgroundColor = 'black';
}
};
</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Event delegation </title>
<style>
* {
padding: 0;
margin: 0;
}
ul {
list-style: none;
overflow: hidden;
margin-top: 80px;
}
ul li {
float: left;
width: 100px;
height: 30px;
text-align: center;
line-height: 30px;
color: #fff;
background-color: #000;
margin: 0 10px
}
</style>
</head>
<body>
<ul id="box">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
var ul = document.querySelector('#box')
/*
var lis = document.querySelectorAll('li')
for (var i = 0; i < lis.length; i++) {
lis[i].onmouseover = function () {
this.style.backgroundColor = 'blue';
};
lis[i].onmouseout = function () {
this.style.backgroundColor = 'black';
};
}*/
// Use event delegation
ul.onmouseover = function(e) {
console.log(e);
if (e.target.nodeName.toLowerCase() === 'li') {
e.target.style.backgroundColor = 'blue';
}
};
ul.onmouseout = function(e) {
if (e.target.nodeName.toLowerCase() === 'li') {
e.target.style.backgroundColor = 'black';
}
};
var li = document.createElement('li');
li.innerHTML = '6';
ul.append(li);
</script>
</body>
</html>6、 ... and 、 Event method
6.1、 Stop the event from bubbling
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Stop the event from bubbling </title>
<style>
.outer {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: blueviolet;
text-align: center;
position: relative;
}
.inner {
width: 200px;
height: 200px;
margin: 50px;
background-color: cornflowerblue;
line-height: 200px;
color: #fff;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"> Inner box </div>
</div>
<script>
var inner = document.querySelector('.inner');
var outer = document.querySelector('.outer');
// When you click inner when , Do not trigger external div Click events for
inner.onclick = function (event) {
console.log('inner')
// Dealing with compatibility issues
if (event.stopPropagation()) {
event.stopPropagation(); // This method is early IE Version not supported
} else {
event.cancelBubble = true; // IE Supported by
}
};
outer.addEventListener('click', function (event) {
console.log('outer');
});
</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Stop the event from bubbling </title>
<style>
.outer {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: blueviolet;
text-align: center;
position: relative;
}
.inner {
width: 200px;
height: 200px;
margin: 50px;
background-color: cornflowerblue;
line-height: 200px;
color: #fff;
}
.outer a {
position: absolute;
bottom: 5px;
left: 10px;
color: white;
text-decoration: none;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"> Inner box </div>
<a href="javascript:void(0)"> Click on </a>
</div>
<script>
var inner = document.querySelector('.inner');
var outer = document.querySelector('.outer');
var a = document.querySelector('a');
// When you click inner when , Do not trigger external div Click events for
inner.onclick = function (event) {
console.log('inner')
// Dealing with compatibility issues
if (event.stopPropagation()) {
event.stopPropagation(); // This method is early IE Version not supported
} else {
event.cancelBubble = true; // IE Supported by
}
};
outer.addEventListener('click', function (event) {
console.log('outer');
});
a.addEventListener('click', function (event) {
console.log('-----')
//event.stopPropagation();
event.stopImmediatePropagation();
});
</script>
</body>
</html>stopPropagation() And stopImmediatePropagation()
The same thing : Can prevent the occurrence of event bubble .
difference :
(1)stopPropagation() Method can only prevent event bubbling , Cannot prevent the execution of the same event for the same object .
6.2、 Blocking default behavior
6.2.1、 Block the default behavior of links
<a href="javascript:void(0)"> TaoBao </a>
<a href="javascript:;"> tencent </a>
<a href="https://www.baidu.com"> Baidu </a>
<script>
var as = document.querySelectorAll('a');
as[2].onclick = function(event) {
//console.log(event);
event.preventDefault();
};
</script>6.2.2、 Prevent the submit button from submitting the default behavior of the form
<p>
<form action="https://www.baidu.com" method="post">
<input type="text" name="s">
<input type="submit" value=" Provide ">
</form>
</p>
<script>
var form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
});
</script>7、 ... and 、 Mouse events

Example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Mouse events </title>
<style>
*{
padding: 0;
margin: 0;
}
body {
height: 2000px;
}
.box {
position: fixed;
top: 0;
left: 0;
width: 300px;
height: 300px;
margin: 50px;
background-color: #ff6700;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box')
box.addEventListener('click', function (event) {
event = event || window.event;
// client It is aimed at the visualization area
console.log(event.clientX, event.clientY);
// page Is for the page
console.log(event.pageX, event.pageY)
// screen It is aimed at the computer screen
console.log(event.screenX, event.screenY);
});
</script>
</body>
</html>边栏推荐
- Eight digit
- BOM(Browser Object Model)
- [NLP] 3 papers on how Stanford team builds a better chat AI
- Introduction to yottastore, a new generation of storage engine for VPC TCE cos
- Monotone stack template
- What are the reasons for the abnormal playback of the online channel of the channel accessed by easycvr national standard protocol?
- Redis series (3) - sentry highly available
- next_ Permutation full permutation function
- SAP license: SAP s/4 Hana module function introduction
- Bigdecimalavoiddoubleconstructorrule: do not directly use the double variable as a parameter to construct BigDecimal
猜你喜欢

(Video + graphics) introduction to machine learning series - Chapter 11 support vector machines
Millions of dollars worth of NFT were stolen in the attack, and Google issued an emergency warning to 3.2 billion users worldwide | February 21 global network security hotspot

Sudoku (easy to understand)

What is decision intelligence?

Network security database penetration of secondary vocational group in 2022

Different JVM
Online sequence flow chart making tool

Graph traversal (BFS and DFS) C language pure handwriting
congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now

微服务系统设计——数据模型与系统架构设计
随机推荐
Mcu-08 interrupt system and external interrupt application
Differences between get and post request modes
微服务系统设计——接口文档管理设计
About pyqt5 to realize paging function (one window implements different interfaces)
如何在 R 中创建线性模型预测区间 并可视化
Leetcode skimming questions - the 72nd biweekly match and 281 weekly match
Get max value of a bit column - get max value of a bit column
Leetcode daily question solution: 717 1-bit and 2-bit characters - reverse order
Five advantages and disadvantages of Bi
腾讯云荣获“可信云技术最佳实践-虚拟化”
He "painted" what a smart city should look like with his oars
视频平台如何将旧数据库导入到新数据库?
An analysis of the comments on the TV series Douban by procedural apes
Four security issues of low code and no code development
110. balanced binary tree
Selection (033) - what is the output of the following code?
Sword finger offer 10- ii Frog jumping on steps
Data driven decision making: Decision intelligence and design thinking
Common MySQL commands of installation free version
[NLP] 3 papers on how Stanford team builds a better chat AI