当前位置:网站首页>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 elementsNodeListaggregate .
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 .innerTextattribute
Add text content to / Update to Any label position
Labels contained in the text Will not be parsed
box.innerText = ' I little interesting ~'
object .innerHTMLattribute
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>
边栏推荐
- About wechat enterprise payment to change x509certificate2 read certificate information, publish to the server can not access the solution
- 基于STM32的OLED 屏幕驱动
- Async/await asynchronous function
- Execute any method of any class through reflection
- std::vector批量导入快速去重方法
- About the loading of layer web spring layer components, the position of the layer is centered
- Hash table acwing 840 Simulated hash table
- 哈希表 AcWing 840. 模拟散列表
- JS7day(事件对象,事件流,事件捕获和冒泡,阻止事件流动,事件委托,学生信息表案例)
- 哈希表 AcWing 841. 字符串哈希
猜你喜欢

BOM DOM

spfa AcWing 852. SPFA judgement negative ring

AI mid stage technology research

Simple use of drools decision table

Distributed machine learning framework and high-dimensional real-time recommendation system

Linear DP acwing 895 Longest ascending subsequence

js1day(输入输出语法,数据类型,数据类型转换,var和let区别)

上手报告|今天聊聊腾讯目前在用的微服务架构

Drools dynamically add, modify, and delete rules

Enhance network security of kubernetes with cilium
随机推荐
Heap acwing 838 Heap sort
Drools dynamically add, modify, and delete rules
Execute any method of any class through reflection
Intel internal instructions - AVX and avx2 learning notes
Is the neural network (pinn) with embedded physical knowledge a pit?
Linear DP acwing 897 Longest common subsequence
[ybtoj advanced training guidance] cross the river [BFS]
FBX import under ue4/ue5 runtime
Js7day (event object, event flow, event capture and bubble, prevent event flow, event delegation, student information table cases)
Some sudden program ideas (modular processing)
Bom Dom
Js6day (search, add and delete DOM nodes. Instantiation time, timestamp, timestamp cases, redrawing and reflow)
一些突然迸发出的程序思想(模块化处理)
浏览器node事件循环
JDBC 预防sql注入问题与解决方法[PreparedStatement]
js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
BOM DOM
Rust search server, rust quick service finding tutorial
js5day(事件监听,函数赋值给变量,回调函数,环境对象this,全选反选案例,tab栏案例)
Dijkstra AcWing 850. Dijkstra finding the shortest circuit II