Mind maps are borrowed from a little sister, thank you little sister, borrowed from the address portal
DOM events are bound to events
What is an event? What is event binding?
Events are the default behavior of the browser, and they exist whether or not based on the JS binding method. The associated event (click event) fires whenever the associated action fires (click event). So, event binding means: binding methods to the event behavior of an element, and when the event is fired, the method executes.
1.1 Mouse Events
Mouse events can be roughly divided into three categories:
- Mousedown, Mousemove, mouseup: Press, move, release the mouse.
- Click, dblclick: Double-click the mouse.
- Mouseover, mouseout: Mouse moves in/out of an element (bubbles).
- Mouseenter, mouseleave: Mouse moves in/out of an element (without bubbling).
The following is a detailed introduction:
Type one: click events
- Click: triggered when the mouse is pressed (usually the main button).
- Dblclick: Triggered when you double click on the same element.
The second type: press events
- Mousedown: Triggered when the mouse button is pressed.
- Mousemove: Triggered when the mouse moves within a node. This event is triggered continuously when the mouse continues to move. To avoid performance problems, it is recommended to restrict the listener function of this event to run only once in a period of time.
- Mouseup: Triggered when the mouse key is released.
Note that the click event means that the user completes the mousedown action and then the Mouseup action in the same location. So, the firing sequence is mousedown first, mouseup next, and Click last. Type 3: move in/move out events
- Mouseenter: Triggered when the mouse cursor moves inside the element for the first time from outside the element. This event does not bubble and does not fire repeatedly when the cursor moves over descendant elements. Usually used with mouseleave.
- Mouseleave: Triggered when the mouse moves away from a node. Leaving the parent node does not trigger this event (more on this later).
- Mouseover: Triggered when the mouse enters a node, and again when entering a child node (see more later).
- Mouseout: Triggered when the mouse moves away from a node, as well as from the parent node (see more later).
Other:
- Contextmenu: triggered when the right mouse button is pressed (before the contextmenu appears), or when the contextmenu key is pressed.
- Wheel: Triggered when the mouse wheel is rolled. This event inherits the WheelEvent interface.
1.2 Keyboard Events
Keyboard events: Triggered when the user performs an action on the page using the keyboard
Keydown: This event is triggered when the user presses any key on the keyboard. If the user holds it down, this event is repeatedly triggered to return the keyCode
Keypress: this event is triggered when the user presses a character key on the keyboard, and this event is repeated if the user holds it down. This event is also triggered when the user presses ESC (charCode, ASCII).
Keyup: When the user releases a key on the keyboard, the input text box is triggered to enter content
1.3 User Interface Events
User interface events: Events that occur when a user interacts with elements on a page, but are not necessarily related to user action.
Load event: this event is triggered on the window when the page has finished loading, on the ING element when the image has finished loading, etc., when the page has finished loading (including all images, JS files, CSS and other external file resources), img will download as soon as SRC is set
Unload events: triggered on the Window when the page is completely unloaded, and so on. Triggered when one page switches to another, this event is often used to clear references and reduce memory leaks
Error: Raised on window when a JS error occurs, or on IMG when the image cannot be loaded
Abort event: When the user stops the download process, it is fired on the object element if the embedded content has not finished loading
Select: Triggered when the user selects one or more characters in a text box (input or Textarea)
Resize: Fires on the window when the size of the window or frame changes
Scroll: Triggered when the user scrolls the contents of an element with a scroll bar
1.4 Focus Events events
Focus event: Emitted when an element gains focus or loses focus
Blur: Triggered when you lose focus, this event does not bubble
Focus: Trigger when you get focus, no bubbles
Focusin: triggered when gaining focus, but it bubbles, DOM3 added
Focusout: Triggered when losing focus, bubbles
1.5 Mobile – applets events
Touchstart: Starts when your finger touches the screen
Touchmove: When a finger moves across the screen
Touchend: Triggered when your finger leaves the screen
Touchcancel: Triggered when forced to abort the slide (bounce message, incoming call, etc.)
Tap: to touch with a finger and move away (tap)
Longtap: After finger touch, more than 350ms away
Event bindings are written the same as component properties, in the form of keys and values.
Key starts with bind or catch and then follows the type of event, such as bindtap, catchtouchStart
1.6 Form Events
1. Obtain the form
The value is obtained by ID. Var form = document.getelementById (” form1 “);
Document. forms allows you to get all the forms on a page. Var firstForm = document.forms[0]; // Get the first form on the page
Var myForm = document.forms[” form2 “]; // Get the form on the page named “form2”
2. Submit the form
Set type of to submit
Set type of
Set type of to image
It should be noted that it is generally disabled after submission
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The form submission</title>
</head>
<body>
<form action="" id="myForm">
<! -- Universal Submit button -->
<input type="submit" value="Submit Form">
<! -- Customize submit button -->
<button type="submit">Submit Form</button>
<! Image button -->
<input type="image" src="icon.png">
</form>
<script type="text/javascript">
var form = document.getElementById("myForm");
form.addEventListener('submit'.function (event) {
alert("Click submit button!!");
// Block submission of ohhh events
event.preventDefault();
})
</script>
</body>
</html>
Copy the code
//javascript can also be programmed to submit forms, but does not trigger the Submit event. Such as:
var form = document.getElementById("myForm");
form.submit();// Submit the form
Copy the code
3. Reset the form
When you reset the form, you reset the form fields to the initial values that the page just loaded. There are two ways to reset a form:
Set type of to reset
Set type of
Note that unlike form submission, programmatically resetting the form initiates a reset event.
Example:
<! DOCTYPE html><head>
<meta charset="UTF-8">
<title>The form submission</title>
</head>
<body>
<form action="" id="myForm">
<input type="text" value="Initial value is text">
<input type="radio" name="danxuankuang"> 男</input>
<input type="radio" value="Female" name="danxuankuang" checked>
女
</input>
<input type="reset">reset</input>
<button type="reset">reset</button>
</form>
</body>
</html>
Copy the code
4. Form field attributes
Each form object has a Elements attribute, which is a collection of all form elements (fields) in the form.
Form fields have common attributes
5. Common methods for form fields
Focus (): The form field gets focus. HTML5 has added an autofocus attribute to form fields. In browsers that support this property, setting this property automatically moves the focus to the field without JavaScript.
Blur (): Form fields lose focus
6. Common events for form fields
Blur: Triggered when the current field loses focus.
Change: For and elements, fired when they lose focus and their value changes; For elements, fired when their options change.
Focus: Triggered when the current field gets focus.
1.7 Audio and Video Events
The HTML5 DOM provides methods, attributes, and events for < Audio > and
methods
- AddTextTrack () adds a new text track to audio/video.
- CanPlayType () checks whether the browser can play the specified audio/video type.
- Load () reloads audio/video elements.
- Play () Starts playing audio/video.
- Pause () Pauses the currently playing audio/video.
See W3C document Portals for more
1.8 Event Binding
1.8.1 DOM0-level Event Binding
Onxxx = function(){}
How it works: Assigns a function to some private attributes of the current element object. We can view these properties when we output an element object in the console. When the event behavior is triggered, the browser JS engine will help us execute the method.
Remove binding: element. Onxxx = null, making this attribute point to an empty object.
Limitations: Since events exist as private attributes, only one method can be bound to the event behavior of the current element, and multiple methods will replace the previous one. You cannot bind methods to events that do not exist in the element’s private attributes.
1.8.1 DOM2-level Event Binding
AddEventListener (‘ XXX ‘,function (){},[false/true]),[] Optional arguments, false by default (executed during bubble phase)
How it works: The element based prototype chain __proto__ finds EventTarget.prototype and uses the built-in addEventListener and removeEventListener for event binding/removal binding (regardless of compatibility).
Underlying principle: Event listener & method binding based on the browser’s built-in event pool mechanism.
function fn1(){}
function fn2(){}
function fn3(){}
box.addEventListener('click',fn1)
box.addEventListener('click',fn2)
box.removeEventListener('click',fn1)
box.removeEventListener('click',fn2)
Copy the code
$(document).ready() in JQ
I’ve seen some of the JQ source code before, which contains $(document).ready() handling
document.addEventListener(“DOMContentLoaded”, completed)
=>1) It is based on DOM2 level event pool listener implementation of event binding, so you can bind the event in the same page many different methods, that is, can be used multiple times
< span style = “max-width: 100%; clear: both; min-height: 1em
Window. onload itself is based on the DOM0 event binding and listens for the load event, so not only can the page be used once, but it will not trigger execution until all browser resources have been loaded, which is later than DOMContentLoaded
.
So when we were working on projects, some of them didn’t use JQ, and I wanted to wait until the DOM structure was loaded to do something, so I wrote some public methods modeled after JQ
Event objects and event propagation mechanisms
1. Event objects
2.1 To bind a mouse click event to an element, the system passes an object to the event function, which can obtain some properties
<! DOCTYPE html><head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="box" style="width: 300px; height: 400px; background-color: purple;">
<div class="box2" style='width:100px; height:100px; background-color:red; '></div>
</div>
<script>
let box = document.querySelector(".box");
box.onclick = function (e) {
console.log(e);// there will be a MouseEvent object MouseEvent
console.log(e.type); //'click' returns the current event type
console.log(e.target); // Box or box2 represents the target element of the event, which is the innermost element of the current clicked region
console.log(e.currentTarget); // Box represents the event source, who registers the event, and currentTarget is who
// Coordinates related attributes
console.log(e.clientX, e.clientY); // The origin of the coordinates is the upper left corner of the browser.
console.log(e.pageX, e.pageY);
/* The origin of the coordinate is the top left corner of the current page. The distance from the top left corner of the page is the same as that of the coordinate
console.log(e.offsetX, e.offsetY); // The origin is the upper left corner of the innermost element of the current click region.
console.log(e.screenX, e.screenY); // The origin of the coordinates is the upper left corner of the current monitor screen.
e.preventDefault(); // indicates the default behavior for canceling events
e.stopPropagation(); / / to prevent further capture of the current event or bubble, but the same layer can't stop, namely stop can use e.s topImmediatePropagation ();
};
</script>
</body>
</html>
Copy the code
2.2 Keyboard event objects
<! DOCTYPE html><head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
document.onkeydown = function (e) {
console.log(e);//KeyboardEvent, type to get this event
console.log(e.keyCode);// Get the corresponding keyboard code
};
</script>
</body>
</html>
Copy the code
2.3 Window. onload event object
window.onload = function (e) {
console.log(e);/ / the Event,
};
Copy the code
2. What is the event default behavior? How do I cancel the default behavior?
Many elements naturally have some default behavior:
- When we click a TAB, the page will be redirected;
- Text box can be entered when the content
- In some cases the text box has input memory
- Press the right mouse button to display the right menu
How do I block the default behavior? With ev. The preventDefault ();
document.oncontextmenu = function (ev) {
// Disable right-click menus
ev.preventDefault();
// return false; This also prevents default behavior
};
Copy the code
3. Event propagation mechanism
There are three default propagation mechanisms for events: event capture, target phase, and bubble phase:
Event capture When a mouse click or dom event is triggered, the browser looks from the outermost hierarchy all the way down until it finds the event source that currently triggered the event. (The purpose is to provide a propagation path for the bubbling phase => ev.path)
The target phase triggers the relevant behavior of the current event source
Bubbling not only triggers the behavior of the current event source, but also triggers the behavior of all ancestor elements. (In this process, methods are triggered to execute which element’s event behavior is bound to, and propagated from the inner layer to the outer layer.)
/ layer structure: the window – > document — — > HTML > body – > the outer – > inner – > center /
<! DOCTYPE html><head>
<meta charset="UTF-8">
<title></title>
<style>
.outer{
width: 400px;
height: 400px;
background-color: pink;
padding:75px 0;
}
.inner{
width: 250px;
height: 250px;
background-color: red;
padding:75px 0;
}
.center{
width: 100px;
height: 100px;
background-color: orange;
}
.vh{
margin: 0 auto;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="outer vh">
outer
<div class="inner vh">inner
<div class="center vh">center</div>
</div>
</div>
<script>
document.body.onclick=function(e){
console.log('BODY',e);
}
var outer=document.querySelector('.outer')
outer.onclick=function(e){
console.log('outer',e);
}
var inner=document.querySelector('.inner')
inner.onclick=function(e){
console.log('inner',e);
}
var center=document.querySelector('.center')
center.onclick=function(e){
// Prevent bubbling propagation
e.stopPropagation()// Click Center to start only his own events
console.log('center',e);
}
</script>
</body>
</html>
Copy the code
Analyze mouseover and mouseEnter
Magnifying glass project
One of the project:
1. Project Presentation:
2. Idea Diagram:
<! DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<title>Document</title>
<! - CSS style -- -- >
<style>
* {
margin: 0;
padding: 0;
}
.small {
position: relative;
width: 400px;
height: 400px;
border: 1px solid # 888888;
margin: 50px;
}
.small img {
width: 400px;
height: 400px;
}
.small .mask {
position: absolute;
top: 0;
height: 0;
width: 150px;
height: 150px;
background-color: rgba(244.245.234.0.3);
cursor: move;
}
.big {
width: 400px;
height: 400px;
border: 1px solid # 888888;
position: absolute;
top: 50px;
left: 470px;
background-image: url("small.jpg");
background-size: 266%;
/* mask/small=big/img-size bg-size=img-size/img size */
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="small">
<img src="small.jpg" alt="" />
<div class="mask"></div>
</div>
<div class="big"></div>
</div>
<script>
let small = document.querySelector(".small");
let mask = document.querySelector(".mask");
let big = document.querySelector(".big");
small.addEventListener("mousemove".function (e) {
// Mouse distance to the upper left of the viewable area
let ClientX = e.clientX;
let ClientY = e.clientY;
// The distance of the small element from the browser boundary
let picT = small.offsetTop;
let picL = small.getBoundingClientRect().left;
// Calculate that 75 is half the width and height of the box
let top = ClientY - picT - 75;
let left = ClientX - picL - 75;
top < 0 ? (top = 0) : top > 250 ? (top = 250) : top;
left < 0 ? (left = 0) : left > 250 ? (left = 250) : left;
mask.style.top = top + "px";
mask.style.left = left + "px";
/* Background-position :50%,50%; The distance the mask moves/the maximum distance is the percentage positioning of the box */
big.style.backgroundPosition =
(left / 250) * 100 + "%" + (top / 250) * 100 + "%";
console.log(big);
});
</script>
</body>
</html>
Copy the code
Project 2: Same idea as above
Project Presentation:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<title>Document</title>
<style>
body {
background-color: #d8e7fa;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
.item_area {
position: relative;
width: 400px;
height: 480px;
border: 1px solid # 888888;
margin: 50px;
}
.item_area .pic {
margin-bottom: 15px;
}
.item_area .pic img {
width: 400px;
height: 400px;
}
.item_area .pic .cover {
position: absolute;
top: 0;
height: 0;
width: 150px;
height: 150px;
background-color: rgba(244.245.234.0.3);
/* background-image: Url, "http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEF3A.cd5SVBGQ98wblceKrKmGMuFRajAVrG8epoZ 3ThAD3WX0R87tWNSsqShuhIkPSQXevJNxYNsOFhbDP0IwDQ! /b&bo=ngGeAQAAAAABFzA! &rf=viewer_4"); * /
}
.item_area .list {
display: flex;
}
/* center */
.item_area .list li {
margin: auto;
}
.item_area .list .current {
border: 2px solid red;
}
.item_area .list img {
width: 50px;
height: 50px;
display: block;
}
.item_area .detail {
width: 400px;
height: 400px;
border: 1px solid # 888888;
position: absolute;
top: 0;
left: 420px;
background-image: url("Http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEE * * OyApeGoKZrvniaEY4v8roNrqMw4s9kl20nHeRQq4 tOrb*JryiRYPqWUOwHgtr1.AqYUuNFvC31czu9Xus9c! /b&bo=IAMgAyADIAMBGT4! &rf=viewer_4");
background-size: 266%;
}
</style>
</head>
<body>
<div class="item_area">
<div class="pic">
<img
src="Http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEE * * OyApeGoKZrvniaEY4v8roNrqMw4s9kl20nHeRQq4 tOrb*JryiRYPqWUOwHgtr1.AqYUuNFvC31czu9Xus9c! /b&bo=IAMgAyADIAMBGT4! &rf=viewer_4"
/>
<div class="cover"></div>
</div>
<ul class="list">
<li>
<img
class="current"
src="Http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEE * * OyApeGoKZrvniaEY4v8roNrqMw4s9kl20nHeRQq4 tOrb*JryiRYPqWUOwHgtr1.AqYUuNFvC31czu9Xus9c! /b&bo=IAMgAyADIAMBGT4! &rf=viewer_4"
/>
</li>
<li>
<img
src="Http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEFFUJb * SjxiRjUm5CqPgRHQJvLtt6K4qJWr7HWFlxoW8 T3tSgtql1w9aUeMSAnMdBb3v1d7UHHwCo2lJenl7EvE! /b&bo=IAMgAyADIAMBGT4! &rf=viewer_4"
/>
</li>
<li>
<img
src="Http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEIVorZ64 * 1 gdi. LE1 * VJ9XFIFCwwKWIwIeAtPrFjVrgs ifWR.StUcRpd7GDUWAH5MKRhdv5VWYchM9WmD8KnSy4! /b&bo=IAMgAyADIAMBGT4! &rf=viewer_4"
/>
</li>
<li>
<img
src="Http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEHk79Ewm5AdRJ.UAIqlM3him5yyJJ2KJrIKgTzNPyX9V aNS0vr4*B2jk7NQfldcx2gXxVDDlgbE07Rf4q4cYirg! /b&bo=IAMgAyADIAMBGT4! &rf=viewer_4"
/>
</li>
<li>
<img
src="Http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEMivVmlhpCyP3T2uilzKFl4kXOuRpkmfUOp7z1xEeFAG 9u7.sTQwGZtj6VZd11b7IUeqEkX8ejHXRo5tsXOrscI! /b&bo=9AH0AfQB9AEBGT4! &rf=viewer_4"
/>
</li>
<li>
<img
src="Http://m.qpic.cn/psc?/V53ysRyG2hb34N3Z4SMG2cU0tw2YGwud/TmEUgtj9EK6.7V8ajmQrEIsKTjdjju63APyAqUvb9nxp8CfdVIbJSOURXmeQ3cz1 07vyVN9t25WjMI9JYZs1f5bc9SkI1agXK29WoT9tlcY! /b&bo=IAMgAyADIAMBGT4! &rf=viewer_4"
/>
</li>
</ul>
<div class="detail"></div>
</div>
<script>
let list = document.querySelector(".list");
let imgs = list.querySelectorAll("img");
let img = document.querySelector(".pic img");
let pic = document.querySelector(".item_area .pic");
let cover = document.querySelector(".cover");
let detail = document.querySelector(".detail");
list.addEventListener("mousemove".function (e) {
if (e.target.tagName == "IMG") {
img.src = e.target.src;
detail.style.backgroundImage = `url("${e.target.src}") `;
imgs.forEach((item) = > {
item.className = "";
});
e.target.className = "current"; }}); pic.addEventListener("mousemove".function (e) {
let ClientX = e.clientX;
let ClientY = e.clientY;
// The distance between the element and the browser boundary
let picT = pic.getBoundingClientRect().top;
let picL = pic.getBoundingClientRect().left;
// Calculate that 75 is half the width and height of the box
let top = ClientY - picT - 75;
let left = ClientX - picL - 75;
top < 0 ? (top = 0) : top > 250 ? (top = 250) : top;
left < 0 ? (left = 0) : left > 250 ? (left = 250) : left;
cover.style.top = top + "px";
cover.style.left = left + "px";
detail.style.backgroundPosition =
(left / 250) * 100 + "%" + (top / 250) * 100 + "%";
});
</script>
</body>
</html>
Copy the code
Project 3: Box off-house effect
Move the mouse into the box and press the left button to drag it freely
Project ideas and some questions:
Mousedown: Start dragging and dragging mousemove: Calculates the latest position of the box at any time, so that the box moves with the mouse mouseup: End Mousemove and Mouseup will lose focus only when the mouse is pressed down: If the mouse moves too fast, the mouse will disengage from the box, the mouse movement outside the box will not trigger the Mousemove, the box will not update its position => Release the mouse outside the box, the mouseup will not trigger the Mousemove and the mousemove will not move out, the mouse will re-enter the box and move regardless of whether the mouse is pressed or not < Solution > : Ie and Firefox: setCapture and releaseCapture can bind elements to the mouse (or remove the binding effect) to prevent loss of mouse focus. Bind the mouseDown event to the box, bind the move and up event to the document, and change the "this" point. Works with all browser mouse focus solutionsCopy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
background: blue;
cursor: move;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<script>
let box = document.getElementById("box");
box.addEventListener("mousedown", down);
// Hold down the mouse to perform the operation
function down(ev) {
// Record where the mouse is pressed and where the box starts (record the value on the element's custom attribute for easy call)
// The left offset of offsetLeft relative to the parent reference
this.boxL = this.offsetLeft;
this.boxT = this.offsetTop;
//this.startX mouse position when pressed
this.startX = ev.clientX;
this.startY = ev.clientY;
console.log(ev.clientX, ev.clientY);
this._MOVE = move.bind(this);
this._up = up.bind(this);
console.log(this._up, this._MOVE);
document.addEventListener("mousemove".this._MOVE);
document.addEventListener("mouseup".this._up);
}
function move(ev) {
let curL = ev.clientX - this.startX + this.boxL,
curT = ev.clientY - this.startY + this.boxT;
this.style.top = curT + "px";
this.style.left = curL + "px";
}
function up(ev) {
console.log(this); //box
document.removeEventListener("mousemove".this._MOVE);
document.removeEventListener("mouseup".this._up);
// console.log(this._up, this._MOVE);
// document.removeEventListener("mousemove", move.bind(this));
// document.removeEventListener("mouseup", up.bind(this));
}
box.addEventListener("drag".function (e) {
console.log(e.offsetX, e.offsetY);
});
</script>
</body>
</html>
Copy the code
3. DOM manipulation
3.1 Obtaining DOM Elements
1. Obtain the specified element by id
document.getElementById(“box”);
Since the id cannot be repeated, the object returns Null if it cannot be found; Pay attention to the point
2. Pass the class name /name name/label name
document.getElementsByClassName(“father”); document.getElementsByName(“test”); document.getElementsByTagName(“div”); Since the class can be repeated, an array containing the label object is returned if it is found, and an empty array is returned if it is not found
3. Get by selector (keep these two methods in mind) querySelector returns only the first element found by the specified selector
document.querySelector(“#box”); document.querySelector(“.father”); document.querySelector(“div>form”);
QuerySelectorAll returns all elements found by the specified selector
let oDivs = document.querySelectorAll(“.father”);
Gets all children of the specified element:
Method one:let oDiv = document.querySelector("div");
console.log(oDiv.children);
The children attribute fetches all the children of the specified elementMethod 2:let oDiv = document.querySelector("div");
console.log(oDiv.childNodes);
// The childNodes attribute retrieves all nodes of the specified element
// Just want to get the element node
for(let node of oDiv.childNodes){
// console.log(node.nodeType);
// if(node.nodeType === 1){
if(node.nodeType === Node.ELEMENT_NODE){
console.log(node); }}Copy the code
What is a node? The DOM object (Document), which holds all of the content on the interface as a tree each part of the HTML page is made up of nodes (tags, text, attributes)
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<title>Document</title>
</head>
<body>
<div>
<h1>1</h1>
<h2>2</h2>
<p class="item">3</p>
<p>4</p>
<span>5</span>
</div>
<script>
/* Gets the child node or child element of the specified element */
let oDiv = document.querySelector("div");
// Gets the first child of the specified node
console.log(oDiv.firstChild); //#text
// Gets the first child of the specified element
console.log(oDiv.firstElementChild); //<h1>1</h1>
// Gets the last child of the specified node
console.log(oDiv.lastChild); //#text
// Gets the last child of the specified element
console.log(oDiv.lastElementChild); //<span>5</span>
/* Get the parent from the child element/parent node */
let item = document.querySelector(".item");
console.log(item.parentElement); //
...
console.log(item.parentNode); //
...
/ / compatibility method and support firefox let parentEle = item. The parentElement | | item. ParentNode;
// console.log(parentEle);
// Get the last adjacent node
console.log(item.previousSibling); //#text
// Get the last adjacent element
console.log(item.previousElementSibling); //<h2>2</h2>
// Get the next adjacent node
console.log(item.nextSibling); //#text
// Get the next adjacent element
console.log(item.nextElementSibling); //<p>4</p>
</script>
</body>
</html>
Copy the code
3.2 Add, delete, modify and check element nodes
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<title>Document</title>
</head>
<body>
<div>
<h1>1</h1>
<h2>2</h2>
<p class="item">3</p>
<p>4</p>
<span>5</span>
</div>
<script>
// 1. Create a node
let oSpan = document.createElement("span");
console.log(oSpan); //<span><span/>
console.log(typeof oSpan); //object
// 2. Add the node (the appendChild method adds the specified element to the end;)
let oDiv = document.querySelector("div");
oDiv.appendChild(oSpan);
let oA = document.createElement("a");
oDiv.appendChild(oA);
// 3. Insert the node
// Get the first p and add a span before p
let oP = document.querySelector("p");
oDiv.insertBefore(oSpan, oP);
// 4. Delete the node
// Note: if you want to delete an element in JS, only the parent element can be deleted
// Elements cannot commit suicide
console.log(oSpan.parentNode); //div... div
oSpan.parentNode.removeChild(oSpan);
// 5. Clone nodes
// Note: cloneNode methods do not clone child elements by default. If you want to clone child elements, pass true
// let newDiv = oDiv.cloneNode(); //
let newDiv = oDiv.cloneNode(true); //
...
console.log(newDiv);
</script>
</body>
</html>
Copy the code
3.3 Element Attribute Operations
Whether the label is created by document or queried, the system will wrap the element as an object and return it to us. When the system wraps the object, it will automatically wrap the attributes of the element into this object, so as long as you get the object, you can get the tag attributes and manipulate the tag attributes.
<img src="images/1.jpg" alt="I am alt222" title="I am the title" />
<script>
// 1. How to obtain element attributes
let oImg = document.querySelector("img");
console.log(oImg.alt);
console.log(oImg.getAttribute("alt"));
// Note: pass the object. Attribute name cannot be used to obtain the value of the custom attribute
// Use the getAttribute method to obtain the value of a custom attribute
// 2. How to modify or add element attributes (setAttribute method if the attribute does not exist, it is added, if the attribute exists, it is modified)
oImg.title = "The new title";
oImg.setAttribute("title"."New title222");
oImg.setAttribute("myname"."Image");
// 3. How to delete element attributes
oImg.alt = "";
oImg.removeAttribute("alt");
</script>
Copy the code
3.4 Element Content operations
<div>I am a div<h1>I am heading</h1>
<p>I am a paragraph</p>
</div>
<script>
// 1. Get the element content
/* The innerHTML fetch contains the tag, while the innerText/textContent fetch does not contain the tag. The content retrieved by the innerText removes Spaces */ at both ends
let oDiv = document.querySelector("div");
console.log(oDiv.innerHTML); // Contain labels, no Spaces
console.log(oDiv.innerText); // No labels, no Spaces
console.log(oDiv.textContent); // No labels, no Spaces
// 2. Set the element content
/* New content will overwrite the original content differences: So if you set the data with innerHTML, the data that contains a label, that's converted to a label and then added to it if you set the data with innerText/textContent, the data that contains a label, that's not converted to a label, it's just set as a string */
oDiv.innerHTML = "< span > I am span < / span >";
console.log(oDiv);
/*
I am span
*/
oDiv.innerText = "< span > I am span < / span >";
console.log(oDiv);
/*
I am span
*/
</script>
Copy the code
3.5 Manipulating element styles
// 1. Set the element style
let oDiv = document.querySelector("div");
// The first way is to add the class name to the element and set the written style
oDiv.className = "box";
// The second way
// Note: In the past CSS style by -, in JS are camel name
// Note: styles added through JS are inline styles that override CSS styles of the same name
oDiv.style.width = "300px";
oDiv.style.height = "300px";
oDiv.style.backgroundColor = "blue";
// 2. Get the element style
// The inline style attribute is obtained via the style attribute;
console.log(oDiv.style.width);
/* CSS attribute values must be obtained using the getComputedStyle method; The getComputedStyle method takes a parameter, which is the element object to fetch; The getComputedStyle method returns an object that holds the CSS style and property values. * /
let style = window.getComputedStyle(oDiv);
console.log(style.width);
Copy the code
3.6 Manipulating element events
1. What is an event?
Interactions between the user and the browser are called events, such as click, move in/out
2. How to bind events to elements?
All HTML tags in JavaScript can add events; Function (){}; The code in function is automatically executed when the corresponding event is raised
let oBtn = document.querySelector("button");
oBtn.onclick = function () {
alert("The button was clicked.");
}
// Note: if we add an event with the same name as the system to the element, the event we add will not override the event added by the system
let oA = document.querySelector("a");
oA.onclick = function () {
alert("Tag A was clicked.");
Override the system event with the same name with the event we added
return false;
}
Copy the code
3.7 JS Timer
<div>
<button id="start">start</button>
<button id="close">The end of the</button>
</div>
<script>
// The timer is closed and started
let startBtn = document.querySelector("#start");
let id = null;
// Start timer after click
startBtn.onclick = function () {
this.disabled = true;
id = setInterval(function () {
console.log("Timer is running.");
}, 1000);
};
let closeBtn = document.querySelector("#close");
// Close timer after click;
closeBtn.onclick = function () {
startBtn.disabled = false;
clearInterval(id);
};
Copy the code
4. Event delegation
Event delegation, generally speaking, is to delegate the event of an element to its parent or more external elements. Its implementation mechanism is event bubbling.
Advantages of event delegation:
1. You only need to delegate the events of the same element to the parent or more external elements. You do not need to bind events to all elements, which reduces memory usage and improves performance.
2. Dynamically added elements do not need to rebind events
Points to note:
The implementation of event delegation relies on bubbling, so events that do not support event bubbling are not suitable for event delegation. Not all event bindings are suitable for event delegates, and improper use can lead to events being bound to elements that do not need to be bound to events.
Simple version:
<body>
<ul>
<li>news</li>
<li>entertainment</li>
<li>The picture</li>
<li>video</li>
<li>music</li>
<li>shopping</li>
</ul>
<script>
let ul = document.querySelector("ul");
ul.addEventListener("click".function (e) {
if (e.target.tagName.toLowerCase() === "li") { fn(e); }});function fn(e) {
e.target.style.color = "red";
e.target.style.backgroundColor = "blue";
}
</script>
</body>
Copy the code
Advanced version:
<! DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8" />
<title>06-JavaScript- Element content manipulation</title>
</head>
<body>
<ul>
<li>news</li>
<li>entertainment</li>
<li>The picture</li>
<li>video</li>
<li>music</li>
<li>shopping</li>
</ul>
<script>
function eventDelegate(parentSelector, targetSelector, events, foo) {
// Trigger the execution of the function
function triFunction(e) {
// Compatibility processing
var event = e || window.event;
// Get the element that the target phase points to
var target = event.target || event.srcElement;
// Get the function of the proxy event
var currentTarget = event.currentTarget;
// Handle matches compatibility
if(! Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector ||function (s) {
var matches = (
this.document || this.ownerDocument
).querySelectorAll(s),
i = matches.length;
while (--i >= 0&& matches.item(i) ! = =this) {}
return i > -1;
};
}
// Traverse the outer layer and match
while(target ! == currentTarget) {// Determine if the element we want is matched
if (target.matches(targetSelector)) {
var sTarget = target;
// Execute the bound function, noting this
foo.call(sTarget, Array.prototype.slice.call(arguments)); } target = target.parentNode; }}// Bind all events one by one if there are multiple events
events.split(".").forEach(function (evt) {
// Multiple parent elements need to be individually bound
Array.prototype.slice
.call(document.querySelectorAll(parentSelector))
.forEach(function ($p) {
$p.addEventListener(evt, triFunction);
});
});
}
eventDelegate("ul"."li"."click".function () {
console.log(this);
this.style.backgroundColor = "red";
});
</script>
</body>
</html>
Copy the code