当前位置:网站首页>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
边栏推荐
- Codeforces Round #784 (Div. 4)
- NLLLoss+log_ SoftMax=CE_ Loss
- Kettle实验 (三)
- What is monitoring intelligent playback and how to use intelligent playback to query video recording
- Data visualization: use Excel to make radar chart
- 108. Convert an ordered array into a binary search tree
- Get trustedinstaller permission
- Cross domain configuration error: when allowcredentials is true, allowedorigins cannot contain the special value "*“
- MySQL small exercise (only suitable for beginners, non beginners are not allowed to enter)
- Yyds dry goods inventory ubuntu18 0.4 install MySQL and solve error 1698: access denied for user ''root' '@' 'localhost' '
猜你喜欢

Kettle实验

MySQL small exercise (only suitable for beginners, non beginners are not allowed to enter)

Program, process, thread; Memory structure diagram; Thread creation and startup; Common methods of thread

What is augmented reality technology? Where can it be used?

Cross domain configuration error: when allowcredentials is true, allowedorigins cannot contain the special value "*“

108. 将有序数组转换为二叉搜索树

kernel-pwn学习(3)--ret2user&&kernel ROP&&QWB2018-core

NPM reports an error: operation not allowed, MKDIR 'C: \ program files \ node JS \ node_ cache _ cacache’

Project upload part

NLLLoss+log_ SoftMax=CE_ Loss
随机推荐
AQS & reentrantlock implementation principle
Little girl walking
How to protect open source projects from supply chain attacks - Security Design (1)
JS case to find the maximum value, reverse the array, bubble sort
Mini - exercice MySQL (seulement pour les débutants, pas pour les non - débutants)
npm ERR! network
Employee probation application (Luzhou Laojiao)
Using sqlmap injection to obtain the account and password of the website administrator
MySQL小練習(僅適合初學者,非初學者勿進)
Go language learning notes - structure | go language from scratch
Applet error: cannot read property'currenttarget'of undefined
Two declaration methods of functions of JS
Machine learning (VI) -- Bayesian classifier
npm报错 :operation not permitted, mkdir ‘C: \Program Files \node js \node_ cache _ cacache’
JSON input of Chapter 14 of kettle paoding jieniu
《信息系统项目管理师总结》第八章 项目干系人管理
Number theory to find the sum of factors of a ^ B (A and B are 1e12 levels)
错题汇总1
I don't understand time, timestamp and time zone. Look at this article
112. Path sum