当前位置:网站首页>Js4day (DOM start: get DOM element content, modify element style, modify form element attributes, setinterval timer, carousel Map Case)
Js4day (DOM start: get DOM element content, modify element style, modify form element attributes, setinterval timer, carousel Map Case)
2022-07-02 12:44:00 【By the Difeng River】
List of articles
- DOM brief introduction
- obtain DOM object
- Set up / modify DOM Element content
- Set up / Modifying elements Common styles attribute
- Set up / Modifying elements style attribute
- Set up / modify Form Elements attribute
- Timer - Intermittent function
- Registration agreement countdown case
- Simple carousel case
DOM brief introduction
DOM(Document Object Model
—— Document object model ) Is used to present and interact with any HTML or XML Document interaction API
obtain DOM object
1. according to CSS Selector to get DOM Elements ( a key )
Select the first element that matches
- grammar :
document.querySelector('css Selectors ')
- Parameters :
Contains one or more valid CSS Selector string - Return value :
CSS Selectors The first element of the match , One HTMLElement object .
If it doesn't match , Then return tonull
.
Select multiple matching elements
- grammar :
document.querySelectorALL('css Selectors ')
- Parameters :
Contains one or more valid CSS Selector string - Return value :
CSS Selectors Matching elementsNodeList
aggregate .
What you get is a Pseudo array :
An array with length and index number
But nopop()
push()
Equal array method
Want to get every object inside , You need to traverse (for) The way to get .
Even if there is only one element , adopt querySelectAll() What you get is also a pseudo array , There's only one element in it
If it doesn't match , Then return tonull
.
Set up / modify DOM Element content
If you want to modify the contents of the label element , You can use the following methods :
document.write()
Method
Only the text content Additional To</body>
Front position
Labels contained in the text Will be parsed
document.write('<strong> I little interesting ~</strong>')
object .innerText
attribute
Add text content to / Update to Any label position
Labels contained in the text Will not be parsed
box.innerText = ' I little interesting ~'
object .innerHTML
attribute
Add text content to / Update to Any label position
Labels contained in the text Will be parsed
box.innerHTML = '<strong> I little interesting ~</strong>'
Set up / Modifying elements Common styles attribute
grammar :
object . attribute = value
// 1. Get elements picture
let pic = document.querySelector('img')
// Operational elements
pic.src = `./images/1.webp`
pic.title = ' I'm the picture '
Set up / Modifying elements style attribute
1. adopt style Attribute operation CSS
Be careful :style Attributes can only be Get and set inline styles , The style defined in the class style passes style Can't get .
let box = document.querySelector('div')
box.style.background = 'skyblue'
box.style.width = '400px'
box.style.marginTop = '100px'
Label selection body when , because body Is the only label , You can write directly document.body.style
document.body.style.backgroundImage = `url(./images/desktop_${
num}.jpg)`
2. Operation class name (className) operation CSS
If you change more styles , Directly through style Property modification is cumbersome , We can do it by means of css The form of class name .
let box = document.querySelector('div')
box.className = 'active'
defects : If div There are classes from the central plains that will cover the original classes ( Because it's equivalent to giving div Of class Reassign ).
3. adopt classList Operation class control CSS
In order to solve className
It is easy to overwrite the previous class name , We can go through classList
Add and delete the class name
box.classList.add('active') // Append a class
box.classList.remove('active') // Delete a class
// Switch classes , Element has active Just delete , No, active Just add
box.classList.toggle('active')
** summary :** Use className and classList The difference between ?
className
You can modify multiple styles at the same time , But directly className
Assignment will overwrite the previous class name
classList
It is convenient to modify less styles , classList
Yes, the addition and deletion do not affect the previous class name
Set up / modify Form Elements attribute
<input type="text" value=" Please enter ">
<button disabled> Button </button>
<input type="checkbox" name="" class="agree">
<script>
// 1. Get elements
let input = document.querySelector('input')
// 2. Value or set value obtain input The value inside can be used value
// console.log(input.value)
input.value = ' Mi phones '
input.type = 'password'
let btn = document.querySelector('button')
// btn.disabled = false // It is equivalent to deleting this attribute
let checkbox = document.querySelector('.agree')
checkbox.checked = 'checked'
</script>
Timer - Intermittent function
1. Turn on timer
let time = setInterval(function () {
document.write(" I'm a countdown <br>")}, 1000)
Be careful :
- Function names do not need parentheses
- The timer has a return value , Back to a Numbers
2. off timer
clearInterval(time) // You can write it in setInterval In the function of
Registration agreement countdown case
<!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>
</head>
<body>
<textarea name="" id="" cols="30" rows="10">
Shrimp catcher registration agreement
</textarea>
<br>
<button class="btn" disabled> I have read the user agreement (6)</button>
<script> let btn = document.querySelector('.btn') let i = 6; function countDown() {
i--; btn.innerHTML = ` I have read the user agreement (${
i})` if (i === 0) {
clearInterval(timer) // Clear timer btn.disabled = false // Open button btn.innerHTML = ` I agree to the agreement ` // Replace text } } let timer = setInterval(countDown, 1000) </script>
</body>
</html>
Simple carousel case
every other 1 Second update picture
<!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> .img-box {
width: 700px; height: 320px; margin: 50px auto 0; background: #000; position: relative; } .img-box .tip {
width: 700px; height: 53px; line-height: 53px; position: absolute; bottom: 0px; background-color: rgba(0, 0, 0, 0.8); z-index: 10; } .img-box .tip h3 {
width: 82%; margin: 0; margin-right: 20px; padding-left: 20px; color: #98E404; font-size: 28px; float: left; font-weight: 500; font-family: "Microsoft Yahei", Tahoma, Geneva; } .img-box .tip a {
width: 30px; height: 29px; display: block; float: left; margin-top: 12px; margin-right: 3px; } .img-box ul {
position: absolute; bottom: 0; right: 30px; list-style: none; z-index: 99; } </style>
</head>
<body>
<div class="img-box">
<img class="pic" src="./images/b01.jpg" alt=" The first 1 The description information of the picture ">
<div class="tip">
<h3 class="text"> Challenge cloud song list , Welocme </h3>
</div>
</div>
<script> let data = [ {
imgSrc: 'images/b01.jpg', title: ' Challenge cloud song list , Welocme ' }, {
imgSrc: 'images/b02.jpg', title: ' Pastoral diary , The story of Shangjing ' }, {
imgSrc: 'images/b03.jpg', title: ' The sweet offensive is back again ' }, {
imgSrc: 'images/b04.jpg', title: ' I'm crazy about singing , Born as a singer ' }, {
imgSrc: 'images/b05.jpg', title: ' Annual campus theme activities ' }, {
imgSrc: 'images/b06.jpg', title: 'pink Teacher's new song is released ,5 month 10 It's officially launched ' }, {
imgSrc: 'images/b07.jpg', title: ' The power train came to Xi'an ' }, {
imgSrc: 'images/b08.jpg', title: ' Iron man 3, Hero town Dongfeng ' }, {
imgSrc: 'images/b09.jpg', title: ' I wait for you with my whole heart ' }, ] let i = 0 // Cannot be in a function for Loop access ( Out of timer , Will be in 1 End function in seconds ), To set the global variable, change it according to the timer i Value function lunbo() {
i++; // get data let dat = data[i]; let img = dat.imgSrc let title = dat.title // Get tag let pic = document.querySelector('.pic') let text = document.querySelector('.text') pic.src = img text.innerHTML = title // Change the tag attribute value if (i === data.length - 1) {
i = -1; // If i=0, Then the first picture will skip the rotation ( Because of the head i++) } } setInterval(lunbo, 1000) </script>
</body>
</html>
边栏推荐
- Redis introduction, scenario and data type
- 8 examples of using date commands
- Docker compose configuration mysql, redis, mongodb
- 上手报告|今天聊聊腾讯目前在用的微服务架构
- 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
- 基于STM32的OLED 屏幕驱动
- Floyd AcWing 854. Floyd finds the shortest path
- Interesting interview questions
- Less than three months after the programmer was hired, the boss wanted to launch the app within one month. If he was dissatisfied, he was dismissed immediately
- 计数类DP AcWing 900. 整数划分
猜你喜欢
线性DP AcWing 897. 最长公共子序列
Heap acwing 839 Simulated reactor
上手报告|今天聊聊腾讯目前在用的微服务架构
What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
Linear DP acwing 896 Longest ascending subsequence II
Browser node event loop
Linear DP acwing 902 Shortest editing distance
Anti shake throttle
Enhance network security of kubernetes with cilium
Js10day (API phased completion, regular expression introduction, custom attributes, filtering sensitive word cases, registration module verification cases)
随机推荐
Leetcode - Sword finger offer 37, 38
Window10 upgrade encountered a big hole error code: 0xc000000e perfect solution
堆 AcWing 839. 模拟堆
Leetcode - Sword finger offer 51 Reverse pairs in an array
接口测试面试题目,你都会了吗?
NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
Rust search server, rust quick service finding tutorial
Browser storage scheme
C#修饰符
JS6day(DOM结点的查找、增加、删除。实例化时间,时间戳,时间戳的案例,重绘和回流)
架构师必须了解的 5 种最佳软件架构模式
Linear DP acwing 897 Longest common subsequence
绕过ObRegisterCallbacks需要驱动签名方法
Heap acwing 838 Heap sort
线性DP AcWing 897. 最长公共子序列
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
线性DP AcWing 898. 数字三角形
Docsify deploy IIS
This "little routine" is set on the dough cake of instant noodles. No wonder programmers are always hungry
. Net, C # basic knowledge