当前位置:网站首页>Js6day (search, add and delete DOM nodes. Instantiation time, timestamp, timestamp cases, redrawing and reflow)
Js6day (search, add and delete DOM nodes. Instantiation time, timestamp, timestamp cases, redrawing and reflow)
2022-07-02 12:40:00 【By the Difeng River】
List of articles
What is? DOM node ?
DOM Every content in the tree is called a node
DOM Classification of nodes ?
- Element nodes ( a key ):
All the labels such asbody
、div
html
Root node - Attribute node :
All attributes such ashref
- Text node :
All the text - other
For example, the text in the label
Find node :
Parent node lookup :
parentNode
attribute- Return the nearest parent node Not found. Return is
null
- grammar
Subelement .parentNode
Close the QR code case :
<style> .erweima {
width: 149px; height: 152px; border: 1px solid #000; background: url(./images/456.png) no-repeat; position: relative; } .close {
position: absolute; right: -52px; top: -1px; width: 50px; height: 50px; background: url(./images/bgs.png) no-repeat -159px -102px; cursor: pointer; border: 1px solid #000; } </style>
<body>
<div class="erweima">
<span class="close"></span>
</div> //5 This one div
<script> let closeBtn = document.querySelectorAll('.close') // Get child nodes console.log(closeBtn.parentNode) // Verify whether it is the parent node for (let i = 0; i < closeBtn.length; i++) {
closeBtn[i].addEventListener('click', function () {
// guanbi[i].parentNode.style.display = 'none' // Change the style of the parent node // this.parentNode.style.display = 'none' // Change the style of the parent node this.parentNode.style.visibility = 'hidden' // Don't use it here display,div Will be occupied console.log(i) }) } </script>
</body>
Find child nodes :
childNodes
( understand , Almost no use )
Get all the child nodes 、 Include text nodes ( Space 、 Line break )、 Comment nodes, etc- children ( a key )
Only get All element nodes
One returned Pseudo array
Parent element .children
Brotherhood search :
- Next sibling node
nextElementSibling
attribute - Last sibling node
previousElementSibling
attribute
let btn = document.querySelector('button')
let two = document.querySelector('.two')
btn.addEventListener('click', function () {
two.style.color = 'red'
two.nextElementSibling.style.color = 'red'
two.previousElementSibling.style.color = 'red'
})
Add node :
- Create nodes
That is to create a new web page element , Then add it to the web page , commonly Create the node first , Then insert the node
Create element node method :
document.creatElement(' Tag name ')
- Add nodes
To see in the interface , You have to insert it into a parent element , Insert into the last child element of the parent element :
// Insert at the end of this parent element
Parent element .appendChild( Elements to insert )
Insert in front of a child element in the parent element
// Insert in front of this parent element
Parent element .insertBefore( Elements to insert , In front of which element )
Learn some codes of online reconstruction cases :
let ul = document.querySelector('ul')
// 1. According to the number of data , Decide this little li The number of
for (let i = 0; i < data.length; i++) {
// 2. Create a small li
let li = document.createElement('li')
// console.log(li)
// 4. Prepare the content first , Additional ,li There is no need to create additional elements for the tags inside
li.innerHTML = ` <img src=${
data[i].src} alt=""> <h4> ${
data[i].title} </h4> <div class="info"> <span> senior </span> • <span> ${
data[i].num}</span> People are learning </div> `
// 3. Append to ul Parent element .appendChild( Subelement )
ul.appendChild(li)
}
Clone node
Clone first and then append !!
cloneNode Will clone an element that is the same as the original tag , Pass in Boolean values in parentheses
if true
, It means that cloning will Include descendant nodes Clone together
if false
, Represents cloning Do not include descendant nodes
The default is false
<ul>
<li> This is an example </li>
</ul>
<script>
let ul = document.querySelector('ul')
let newUL = ul.cloneNode(true) // Clone first ,true Clone together on behalf of descendant nodes
// console.log(newUL)
document.body.appendChild(newUL) // Append to parent element body in
</script>
Delete node
- If a node is no longer needed in the page , You can delete it
- stay JavaScript Native DOM In operation , To delete an element, you must pass The parent element is deleted
- grammar
Parent element .removeChild( Elements to delete )
- notes :
If there is no parent-child relationship, the deletion is unsuccessful
Delete nodes and hide nodes (display:none
) There is a difference : Hidden nodes still exist , But delete , Fromhtml
Delete node .
<button> Click on </button>
<ul>
<li> This is an example </li>
</ul>
<script>
// Click button , Delete small li
let ul = document.querySelector('ul')
let btn = document.querySelector('button')
btn.addEventListener('click', function () {
ul.removeChild(ul.children[0])
})
Instantiation (new)
<script>
//new Instantiation Time object
let date = new Date() // Create a time object and get the time , If empty, you will get the current time
document.write(date) // Output Sun Jun 26 2022 21:40:42 GMT+0800 ( China standard time )
</script>
Be careful : The values of month and week should be +1 It's normal !!
Case study :
let arr = [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday ']
let div = document.querySelector('div')
// First call , You don't have to 1 A blank period of seconds
getTime() // There will be no blank period
setInterval(getTime, 1000)
function getTime() {
// 1. Instantiate the time object It must be written into the timer before it can amount
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth() + 1
let date1 = date.getDate()
let hour = date.getHours()
let min = date.getMinutes()
let sec = date.getSeconds()
let day = date.getDay()
div.innerHTML = ` It's today : ${
year} year ${
month} month ${
date1} Japan ${
hour}:${
min}:${
sec} ${
arr[day]}`
}
Time stamp :
What is a timestamp
Refer to 1970 year 01 month 01 Japan 00 when 00 branch 00 The number of milliseconds from seconds to now , It is a special way of measuring time
There are three ways to get time :
date.getTime()
Need to instantiate+new Date()
Use
Date.now()
The point is to remember +new Date()
Because you can return the current timestamp or The specified time stamp
There is no need to instantiate , But you can only get the current timestamp , The first two can return the timestamp of the specified time
// The first one is
console.log(Date.now()) //1656332467573
// The second kind
date = new Date()
console.log(date.getTime()) //1656332467573
// The third kind of
console.log(+new Date()) // The current timestamp 1656332467573
console.log(+new Date('2022-6-27 12:00:00')) // Timestamp of the specified time
How does the browser render the interface
- analysis (Parser)HTML, Generate DOM Trees (DOM Tree)
- At the same time, analyze (Parser) CSS, Generate style rules (Style Rules)
- according to DOM Tree and style rules , Generate Render tree (Render Tree)
- Make a layout Layout( backflow / rearrangement ): According to the generated render tree , Get the geometric information of the node ( Location , size )
- Drawing Painting( Repaint ): Draw the whole page according to the calculated and obtained information
- Display: Displayed on the page
Redraw and reflow ( rearrangement )
backflow ( rearrangement )
When Render Tree Of some or all of the elements in Size 、 structure 、 Layout When something changes , The browser will re render some or all of the documents
Cheng is called backflow .
Repaint
Due to the node ( Elements ) Changes in the style of It does not affect its position in the document flow and document layout when ( such as :color、background-color、
outline etc. ), be called Repaint .
Redrawing does not necessarily cause reflow , And reflow must cause redrawing .
A perfect case of off-duty countdown that I modified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style> .countdown {
width: 240px; height: 305px; text-align: center; line-height: 1; color: #fff; background-color: brown; /* background-size: 240px; */ /* float: left; */ overflow: hidden; } .countdown .next {
font-size: 16px; margin: 25px 0 14px; } .countdown .title {
font-size: 33px; } .countdown .tips {
margin-top: 80px; font-size: 23px; } .countdown small {
font-size: 17px; } .countdown .clock {
width: 142px; margin: 18px auto 0; overflow: hidden; } .countdown .clock span, .countdown .clock i {
display: block; text-align: center; line-height: 34px; font-size: 23px; float: left; } .countdown .clock span {
width: 34px; height: 34px; border-radius: 2px; background-color: #303430; } .countdown .clock i {
width: 20px; font-style: normal; } </style>
</head>
<body>
<div class="countdown">
<p class="next"> It's today 2021 year 8 month 28 Japan </p>
<p class="title"> The countdown to work </p>
<p class="clock">
<span id="hour">00</span>
<i>:</i>
<span id="minutes">00</span>
<i>:</i>
<span id="scond">00</span>
</p>
<p class="tips">
Now it is 18:30:00
</p>
</div>
<script> // Get elements let next = document.querySelector('.next') let clock = document.querySelector('.clock') // Acquisition time getTime() setInterval(getTime, 500) function getTime() {
let date = new Date() let year = date.getFullYear() let month = date.getMonth() + 1 let day = date.getDate() let hour = date.getHours() let minute = date.getMinutes() let second = date.getSeconds() // Display the current time next.innerHTML = ` It's today ${
year} year ${
month} month ${
day} Japan ` let time = TimeMachine(hour, minute, second) // Time converter <10 Just add '0' clock.nextElementSibling.innerHTML = ` Now it is ${
time[0]}:${
time[1]}:${
time[2]}` // Timestamp calculation now = +new Date() future = +new Date(`${
year}-${
month}-${
day} 22:00:00`) // future = +new Date(`${year}-${month}-${day} 22:00:00`) console.log(future) total = (future - now) / 1000 // Convert to seconds if (total <= 0) {
return } // Show countdown let h = parseInt(total / 60 / 60 % 24) // Calculating hours let m = parseInt(total / 60 % 60); // score let s = parseInt(total % 60); // Calculate the current seconds let time2 = TimeMachine(h, m, s) // Time converter <10 Just add '0' clock.children[0].innerHTML = time2[0] clock.children[2].innerHTML = time2[1] clock.children[4].innerHTML = time2[2] } // Time converter <10 Just add '0' function TimeMachine(hour, minute, second) {
hour = hour < 10 ? '0' + hour : hour // Less than 10 repair 0, Don't forget to give it again h assignment minute = minute < 10 ? '0' + minute : minute second = second < 10 ? '0' + second : second return [hour, minute, second] } </script>
</body>
</html>
Weibo publishes part of the code of the case ( After modification ):
let area = document.querySelector('#area')
let useCount = document.querySelector('#useCount')
let send = document.querySelector('#send')
area.addEventListener('input', function () {
useCount.innerHTML = this.value.length
}
)
send.addEventListener('click', function () {
if (area.value.trim() === '') {
// Meaningless space entry is prevented , Use string .trim() Remove leading and trailing spaces
alert(' Cannot be null !')
area.value = ''
useCount.innerHTML = '0'
return
}
let list = document.querySelector('#list')
let li = document.createElement('li')
let random = Math.floor(Math.random() * dataArr.length)
// Use time objects to make time dynamic new Date().toLocaleString()
li.innerHTML = ` <div class="info"> <img class="userpic" src=${
dataArr[random].imgSrc} /> <span class="username">${
dataArr[random].uname}</span> <p class="send-time">${
new Date().toLocaleString()}</p> </div> <div class="content">${
area.value}</div> <span class="the_del">X</span> `
list.insertBefore(li, list.children[0])
// Reset the form field content to empty
// take userCount Reset the contents to 0
area.value = ''
useCount.innerHTML = '0'
let del = li.querySelector('.the_del') // Use li.querySelector()
del.addEventListener('click', function () {
list.removeChild(li)
})
})
边栏推荐
- High performance erasure code coding
- js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
- 上传文件时,服务器报错:IOFileUploadException: Processing of multipart/form-data request failed. 设备上没有空间
- [ybtoj advanced training guide] similar string [string] [simulation]
- 怎样写一篇赏心悦目的英文数学论文
- Multiply LCA (nearest common ancestor)
- About wechat enterprise payment to change x509certificate2 read certificate information, publish to the server can not access the solution
- Does C language srand need to reseed? Should srand be placed in the loop? Pseudo random function Rand
- 寻找二叉树中任意两个数的公共祖先
- SparkContext: Error initializing SparkContext解决方法
猜你喜欢
async/await 异步函数
Redis sentinel mechanism and configuration
"As a junior college student, I found out how difficult it is to counter attack after graduation."
AAAI 2022 | Peking University & Ali Dharma Institute: pruning and compression of pre training language model based on comparative learning
Sparkcontext: error initializing sparkcontext solution
JDBC 预防sql注入问题与解决方法[PreparedStatement]
Dijkstra AcWing 850. Dijkstra求最短路 II
深拷貝 事件總線
arcgis js 4. Add pictures to x map
Performance tuning project case
随机推荐
PR 2021 quick start tutorial, learn about the and functions of the timeline panel
MySQL and PostgreSQL methods to grab slow SQL
Writing method of then part in drools
bellman-ford AcWing 853. 有边数限制的最短路
Lombok common annotations
Interview with meituan, a 34 year old programmer, was rejected: only those under the age of 30 who work hard and earn little overtime
Find the common ancestor of any two numbers in a binary tree
Drools executes the specified rule
Visual studio efficient and practical extension tools and plug-ins
Use MySQL events to regularly perform post seven world line tasks
软件测试面试题-2022年大厂面试题合集
1380. Lucky numbers in the matrix [two-dimensional array, matrix]
The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
Adding database driver to sqoop of cdh6
[I'm a mound pytorch tutorial] learning notes
模块化 CommonJS ES Module
Why do programmers have the idea that code can run without moving? Is it poisonous? Or what?
堆 AcWing 838. 堆排序
arcgis js 4.x 地图中加入图片
The differences and relationships among port, targetport, nodeport and containerport in kubenetes