当前位置:网站首页>JS DOM event
JS DOM event
2022-04-23 09:27:00 【Small white egg tart】
Catalog
One 、 Element creates events in two ways
2、 Event monitoring addEventListener W3C recommend
3、 ... and 、DOM Flow of events
Four 、 What is an event object
1、e.target and this The difference between
2、 Blocking default behavior ( Like not letting a Tag jump )
3、 Stop the event from bubbling
6、 ... and 、 Disable selection and disable right-click menu
7、 ... and 、 Get the coordinates of the mouse on the page
8、 ... and 、 Common keyboard events
Case study : Simulate Jingdong key input content
Case study : Simulate JD express to enter the order number
One 、 Element creates events in two ways
1、 The traditional way
on The first event , The uniqueness of the event , Only one processing function can be set for the same event of an element , The back covers the front , The following code only pops up 2.
var btns = document.querySelectorAll('button');
btns[0].onclick = function() {
alert(1);
}
btns[0].onclick = function() {
alert(2);
}
2、 Event monitoring addEventListener W3C recommend
element.addEventListener(type,listener,useCapture)
type: Event type string click mouseover No need to bring it on
listener: Event handler , This function is called when the event occurs
useCapture: Optional parameters , It's a Boolean value , Default false
The following codes pop up in turn 22,33
btns[1].addEventListener('click', function() {
alert(22);
})
btns[1].addEventListener('click', function() {
alert(33);
})
You can also write
btns[1].addEventListener('click', fn)
function fn() {
alert(22);
}
attachEvent understand IE9 Former
Two 、 Delete event
removeEventListener
Click on div It will pop up , The requirement is not to pop up after clicking once , Delete this event .
// Tradition
var divs = document.querySelectorAll('div');
divs[0].onclick = function() {
alert(1);
divs[0].onclick = null;
}
//
divs[1].addEventListener('click', fn) // Inside fn You don't need to call with parentheses
function fn() {
alert(2);
divs[1].removeEventListener('click', fn);
}
3、 ... and 、DOM Flow of events
Event flow describes the order in which the page receives events
Events are propagated between element nodes in a specific order when they occur , This transmission process is called DOM Flow of events .
There are three stages
Capture phase gradually
Current target stage
bubbling phase Spread it up
js The code can only execute one of the capture or bubbling phases ,onclick and attachEvent() You can only get the bubbling stage
// Capture phase If the third parameter is true Is in the capture phase
// var son = document.querySelector('.son')
// son.addEventListener('click', function() {
// alert('son');
// }, true)
// var fa = document.querySelector('.father')
// fa.addEventListener('click', function() {
// alert('fa');
// }, true)
// bubbling phase If the third parameter false Or omit gengguanzhu
var son = document.querySelector('.son')
son.addEventListener('click', function() {
alert('son');
}, false)
var fa = document.querySelector('.father')
fa.addEventListener('click', function() {
alert('fa');
}, false)
document.addEventListener('click', function() {
alert('ss');
})
The capture phase pops up in turn fa,son
The bubbling stage pops up in turn ss fa son( The third parameter is zero false Or when omitted )
Four 、 What is an event object
event It's an event object , Listen for... In parentheses of function , It can be seen as a formal parameter , Event objects exist only when they have events , It is automatically created by the system , We don't need to pass parameters
The event object is a collection of our series of related events , Related to the event , For example, a mouse click contains information about the mouse , Mouse coordinates, etc , If it is keyboard operation , It will include which key was pressed .
div.addEventListener('click',function(event){
console.log(event);
// We can name this event object ourselves ,event evt e
// Compatibility issues ie678 adopt window.eventb
})
1、e.target and this The difference between
e.target The object that triggers the event is returned .this What is returned is the element of the binding event
var ul = document.querySelector('ul');
ul.addEventListener('click', function(e) {
// this Point to ul
console.log(this); // Click on li Print out ul
console.log(e.target); // Print out li Click on li
})
2、 Blocking default behavior ( Like not letting a Tag jump )
e.preventDefault()//DOM The recommended Standard writing
<a href="http://www.baidu.com"> Baidu </a>
var a = document.querySelector('a');
a.addEventListener('click', function(e) {
e.preventDefault(); //dom The recommended Standard writing
})
// Tradition
// a.onclick = function(e){
// e.preventDefault();//1.
// // Low version
// e.returnValue;//2 Method
// return false; // No compatibility characteristic return The latter is not implemented
// }
3、 Stop the event from bubbling
e.stopPropagation()
It won't go up , It just pops up son
// e.cancelBubble = true;// Nonstandard
// if(e && e.stopPropagation){
// e.stopPropagation();
// }else {
// window.event.cancelBubble = true;
// } Compatibility writing
5、 ... and 、 Event delegation
principle : No separate event listeners are set for each child node , Instead, the event listener is set on the parent node , Then the bubble principle is used to affect each child node , We add events to the parent node , When e.target You can get the source element of the trigger event , Using the bubbling principle , The event of the parent element will be triggered .
The tradition is to give everyone li All bound Events .
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
lis[i].addEventListener('click', function() {
for (var i = 0; i < lis.length; i++) {
lis[i].style.backgroundColor = '';
}
this.style.backgroundColor = 'pink';
})
}
Use event delegation , Just give their parent node ul add to , whenever e.target Clicked , Using the bubbling principle , It will trigger ul Click events for , And then again ul Pass through e.target You can get the real trigger li.
ul.addEventListener('click', function(e) {
// alert(' To know whether ');
// Exclusive thoughts
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].style.backgroundColor = '';
}
// e.target We can get the object we click
e.target.style.backgroundColor = 'pink';
})
6、 ... and 、 Disable selection and disable right-click menu
// No right mouse button contextmenu
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
})
// Do not select selectstart Start selecting
document.addEventListener('selectstart', function(e) {
e.preventDefault();
})
7、 ... and 、 Get the coordinates of the mouse on the page
document.addEventListener('click', function(e) {
console.log(e.clientX);
console.log(e.clientY);
// Get the coordinates within the visual area With or without scrollbars The mouse is in the visible area 、
console.log(e.pageX);
console.log(e.pageY);
// If there is a scroll bar , After rolling , Same location in the viewing area , The coordinates will be different
})
Case study : Follow the mouse
<style>
div {
position: absolute;
width: 20px;
height: 20px;
background-color: aqua;
border-radius: 10px;
}
</style>
<body>
<div></div>
<script>
var div = document.querySelector('div');
document.addEventListener('mousemove', function(e) {
//mousemove Just move the mouse 1px Will trigger this event
// Every time you move the mouse, you will get the latest coordinates Put this xy The coordinates are used as the coordinates of the picture top and left value
var x = e.pageX;
var y = e.pageY;
console.log(x);
console.log(y);
// Give the coordinates to the picture
div.style.left = x - 10 + 'px';
div.style.top = y - 10 + 'px'; // Be sure to splice strings
})
</script>
</body>
8、 ... and 、 Common keyboard events
keyup keydown keypress( and keydown similar , But you can't recognize the function keys ,ctrl,shift...)
keyup It bounced up keydown and keypress It's all pressed ( characteristic : Trigger when pressed , The word hasn't gone in yet )
Execution order keydown,keypress,keyup
keyup and keydown Case insensitive ,keypress distinguish
In the keyboard event object keyCode Property to get the corresponding key ASCII value
Case study : Simulate Jingdong key input content
focus() Focus of attention
<!-- Detect whether the user pressed s key , Press and set the cursor in the search box
keyCode Judge The search box gets focus focus() -->
<form action="">
<input type="text">
</form>
<script>
var input = document.querySelector('input');
document.addEventListener('keyup', function(e) {
if (e.keyCode === 65) {
input.focus();
}
})
// up Trigger when talking about It means that it has been installed down Press and it will So the a Write in
</script>
Case study : Simulate JD express to enter the order number
<!-- Express input , The big box above will show At the same time, the font size inside will become larger 、
The form detects user input Add keyboard events to the form
At the same time, the values in the form are obtained to make content for the large box -->
<!-- down press characteristic Trigger when pressed The word hasn't gone in yet -->
<div class="search">
<div class="box"></div>
<input type="text" value=" Please input the express number ">
</div>
<script>
var div = document.querySelector('.box');
var input = document.querySelector('input');
input.addEventListener('keyup', function() {
// Do not display when there is no input
if (this.value == '') {
div.style.display = 'none';
} else {
div.style.display = 'block';
div.innerHTML = input.value;
}
})
input.addEventListener('blur', function() {
// Lose focus , Big box hidden
div.style.display = 'none';
// this.value = ' Please enter ';
})
input.addEventListener('focus', function() {
this.value = '';
if (this.value != '') {
div.style.display = 'block';
}
})
版权声明
本文为[Small white egg tart]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230624113836.html
边栏推荐
- Summary of wrong questions 1
- Creation of raid0 and RAID5 and Simulation of how RAID5 works
- The most concerned occupations after 00: civil servants ranked second. What was the first?
- Distributed message oriented middleware framework selection - Digital Architecture Design (7)
- 考研线性代数常见概念、问题总结
- To remember the composition ~ the pre order traversal of binary tree
- 3、 6 [Verilog HDL] gate level modeling of basic knowledge
- Harbor enterprise image management system
- js 原型链的深入
- web页面如何渲染
猜你喜欢
[reading notes] Chapter 5 conditional statements, circular statements and block statements of Verilog digital system design tutorial (with answers to thinking questions)
Machine learning (VI) -- Bayesian classifier
NPM reports an error: operation not allowed, MKDIR 'C: \ program files \ node JS \ node_ cache _ cacache’
Summary of wrong questions 1
Leetcode题库78. 子集(递归 c实现)
Leetcode-199 - right view of binary tree
kettle庖丁解牛第14篇之JSON输入
How to protect open source projects from supply chain attacks - Security Design (1)
三、6【Verilog HDL】基础知识之门级建模
108. Convert an ordered array into a binary search tree
随机推荐
RSA encryption and decryption signature verification
Two methods of building Yum source warehouse locally
Little girl walking
First principle mind map
LGB, XGB, cat, k-fold cross validation
What is monitoring intelligent playback and how to use intelligent playback to query video recording
搞不懂时间、时间戳、时区,快来看这篇
《數字電子技術基礎》3.1 門電路概述、3.2 半導體二極管門電路
Pre parsing of JS
Go language learning notes - exception handling | go language from scratch
ATSS(CVPR2020)
Leetcode-199 - right view of binary tree
653. 两数之和 IV - 输入 BST
EmuElec 编译总结
108. Convert an ordered array into a binary search tree
【读书笔记】《Verilog数字系统设计教程》 第5章 条件语句、循环语句和块语句(附思考题答案)
Give the method of instantiating the object to the new object
I don't understand time, timestamp and time zone. Look at this article
Thread scheduling (priority)
Set the maximum width of the body, but why does the background color of the body cover the whole page?