当前位置:网站首页>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>边栏推荐
- Tencent cloud TCS: an application-oriented one-stop PAAS platform
- Selection (031) -cool_ How long can secret be accessed?
- Top ten popular codeless testing tools
- Data driven decision making: Decision intelligence and design thinking
- Mariana Trench, Facebook's open source code analysis tool
- How MySQL works - Chapter 14
- Implementation of pure three-layer container network based on BGP
- 【你真的会用ES吗】ES基础介绍(一)
- Digital transformation informatization data planning and technology planning
- What is business intelligence (BI)?
猜你喜欢

Considerations for it project demand analysis

Top ten popular codeless testing tools

Specification for self test requirements of program developers
Business based precipitation component = & gt; manage-table

ASP. Net hosting uploading file message 500 error in IIS

Number of occurrences of numbers in the array (medium difficulty)

Ten excellent business process automation tools for small businesses

微服务系统设计——接口文档管理设计

Five skills of selecting embedded programming language

Redis learning -- list of redis operations
随机推荐
Sudoku (easy to understand)
360 digital released information security trends in January: 120000 fraud risks were captured and users were reminded 2.68 million times
About pyqt5 to realize paging function (one window implements different interfaces)
电子元器件行业B2B电商市场模式、交易能力数字化趋势分析
Why are more and more people studying for doctors? Isn't it more and more difficult to graduate a doctor?
Business based precipitation component = & gt; manage-table
Uniapp wechat applet calls mobile map to navigate to the target point
ASP. Net hosting uploading file message 500 error in IIS
Digital transformation informatization data planning and technology planning
Mcu-08 interrupt system and external interrupt application
Regression testing strategy for comprehensive quality assurance system
JDBC writes Chinese garbled code to the database
Selection (030) - what is the output of the following code?
Ultimate Guide: comprehensive analysis of log analysis architecture of Enterprise Cloud native PAAS platform
Selection (032) - what is the output of the following code?
Nine practical guidelines for improving responsive design testing
Creating a new MySQL user in Amazon RDS environment - creating a new MySQL user in Amazon RDS environment
Selection (031) -cool_ How long can secret be accessed?
Bigdecimalavoiddoubleconstructorrule: do not directly use the double variable as a parameter to construct BigDecimal
如何在 R 中执行幂回归