目錄
- DOM
- Web API 基本概念
- 作用和分類
- 什么是 DOM
- DOM 樹
- DOM 對象
- 獲取 DOM 元素
- 根據 CSS 選擇器來獲取 DOM 元素
- 選擇匹配的第一個元素
- 選擇匹配的多個元素
- 其他獲取 DOM 元素方法
- 修改元素的內容
- 對象.innerText 屬性
- 對象.innerHTML 屬性
- 案例:年會抽獎
- 修改元素屬性
- 修改元素常用屬性
- 修改元素樣式屬性
- 通過 style 屬性操作 CSS
- 利用 className 操作 CSS
- 通過 classList 操作類以控制 CSS
- 案例:輪播圖(初級)
DOM
Web API 基本概念
作用和分類
作用:使用 JavaScript 去操作 html 和瀏覽器
分類:DOM(文檔對象模型)、BOM(瀏覽器對象模型)
什么是 DOM
DOM 定義:DOM(Document Object Model—— 文檔對象模型)是用來呈現以及與任意 HTML 或 XML 文檔交互的 API
白話文解釋:DOM 是瀏覽器提供的一套專門用來操作網頁內容的功能
DOM 作用:開發網頁內容特效、實現用戶交互
DOM 樹
DOM 樹定義:將 HTML 文檔以樹狀結構直觀表現出來,稱為文檔樹或 DOM 樹
性質:描述網頁內容關系的名詞
作用:直觀體現標簽與標簽之間的關系
DOM 對象
DOM 對象:
- 瀏覽器根據 HTML 標簽生成的 JS 對象
- 所有標簽屬性均可在該對象上找到,修改對象屬性會自動映射到標簽
DOM 的核心思想:將網頁內容當作對象來處理
document 對象:
- 是 DOM 提供的對象,其屬性和方法用于訪問、操作網頁內容(如
document.write()
) - 網頁所有內容都包含在
document
中
獲取 DOM 元素
根據 CSS 選擇器來獲取 DOM 元素
選擇匹配的第一個元素
語法:
document.querySelector('CSS選擇器')
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link rel="shortcut icon" href="#" /><style>.box{width: 100px;height: 100px;}</style>
</head>
<body><div class="box">123</div><div class="box">abc</div><p id="nav">導航欄</p><script>const box1 = document.querySelector('div');console.dir(box1);const box2 = document.querySelector('.box');console.dir(box2);const nav = document.querySelector('#nav');console.dir(nav);</script>
</body>
</html>
結果如下:
屏幕錄制 2025-03-28 173922
注意事項:
- 參數:包含一個或多個有效的 CSS 選擇器字符串
- 返回值:CSS 選擇器匹配的第一個元素,一個 HTMLElement 對象;如如果沒有匹配到,則返回 null
選擇匹配的多個元素
語法:
document.querySelectorAll('CSS選擇器')
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link rel="shortcut icon" href="#" /><style>.box{width: 100px;height: 100px;}</style>
</head>
<body><div class="box">123</div><div class="box">abc</div><ul><li></li><li></li><li></li><li></li><li></li></ul><script>const box = document.querySelectorAll('div');console.dir(box);const lis = document.querySelectorAll('ul li');console.dir(lis);</script>
</body>
</html>
結果如下:
注意事項:
- 參數:包含一個或多個有效的 CSS 選擇器字符串
- 返回值:CSS 選擇器匹配的 NodeList 對象集合
- 得到一個偽數組:
- 有長度有索引號的數組
- 但是沒有 pop()、push() 等數組方法
- 想要得到里面的每一個對象,則需遍歷獲得
- 就算只有一個元素,querySelectorAll() 獲取的也是一個偽數組
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link rel="shortcut icon" href="#" /><style>.box{width: 100px;height: 100px;}</style>
</head>
<body><ul class="nav"><li>111</li><li>222</li><li>333</li><li>444</li><li>555</li></ul><script>const lis = document.querySelectorAll('.nav li');console.dir(lis);for(let i = 0; i < lis.length; i++){console.dir(lis[i]); }</script>
</body>
</html>
結果如下:
其他獲取 DOM 元素方法
根據 id 獲取一個元素
document.getElementById('id選擇器')
根據標簽獲取一類元素,獲取所有 div
document.getElementsByTagName('div')
根據類名獲取元素,獲取頁面所有類名為 w 的
document.getElementsByClassName('w')
修改元素的內容
對象.innerText 屬性
將文本內容添加/更新到任意標簽位置
顯示純文本,不解析標簽
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><span class="info">看客老爺真的很帥</span><script>const info = document.querySelector('.info')// 獲取標簽內部的文字內容console.log(info.innerText)// 修改標簽內部的文字內容info.innerText = '看客老爺不是一般的帥' console.log(info.innerText)// 不會解析標簽info.innerText = '<h1>看客老爺</h1>'console.log(info.innerText)</script>
</body>
</html>
結果如下:
對象.innerHTML 屬性
將文本內容添加/更新到任意標簽位置
會解析標簽,多標簽建議使用模板字符
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><span class="info">看客老爺真的很帥</span><script>const info = document.querySelector('.info')// 獲取標簽內部的文字內容console.log(info.innerHTML)// 修改標簽內部的文字內容info.innerHTML = '看客老爺不是一般的帥' console.log(info.innerHTML)// 會解析標簽info.innerHTML = '<h1>看客老爺</h1>'console.log(info.innerHTML)</script>
</body>
</html>
結果如下:
案例:年會抽獎
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.wrapper {width: 840px;height: 420px;background: url(./img/1.jpg) no-repeat center / cover;padding : 100px 250px;box-sizing: border-box;}</style>
</head>
<body><div class="wrapper"><strong>年會抽獎</strong><h1>一等獎:<span id="one">???</span></h1><h2>二等獎:<span id="two">???</span></h2><h3>三等獎:<span id="three">???</span></h3></div><script>const person = ['Jack','Tom','Jerry','Mary','Mike','Lily','Rose'];const prizeIds = ['one', 'two', 'three'];// 使用 for 循環來簡化代碼for (let i = 0; i < prizeIds.length; i++) {const random = Math.floor(Math.random() * person.length);const prizeElement = document.querySelector(`#${prizeIds[i]}`);prizeElement.innerHTML = person[random];person.splice(random, 1);}</script>
</body>
</html>
結果如下:
修改元素屬性
修改元素常用屬性
可通過 JS 設置 / 修改標簽元素屬性,例如利用 src
更換圖片。
常見屬性:href
、title
、src
等。
語法:對象.屬性 = 值
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><img src="./img/1.png" alt=""><script>// 獲取圖片const img = document.querySelector('img')// 修改圖片對象的src屬性img.src = './img/2.png'// 修改圖片的title屬性img.title = '這是第二張圖片'</script>
</body>
</html>
結果如下:
修改元素樣式屬性
可通過 JS 設置 / 修改標簽元素樣式屬性
- 例如輪播圖小圓點自動更換顏色樣式
- 點擊按鈕滾動圖片(涉及圖片位置
left
等樣式調整)
通過 style 屬性操作 CSS
語法:對象.style.樣式屬性 = '值'
代碼示例:
<!DOCTYPE html>
<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: 200px;height: 200px;background-color: black; }</style>
</head>
<body><div class="box"></div><script>const box = document.querySelector('.box');// 修改樣式屬性box.style.width = '300px';box.style.height = '100px';box.style.backgroundColor = 'red';box.style.borderRadius = '50px'box.style.border = '10px solid black'</script>
</body>
</html>
結果如下:
注意事項:
- 修改樣式通過 style 屬性引出
- 如果屬性有 - 連接符,需要轉換為小駝峰命名法
- 賦值的時候,不要忘記加 CSS 單位
利用 className 操作 CSS
場景:修改樣式較多時,借助 CSS 類名比直接通過 style
屬性修改更便捷
語法:元素.className = '類名'
(示例:active
為 CSS 類名時,元素.className = 'active'
)
代碼示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div {width: 200px;height: 200px;background-color: black; }.box{width: 300px;height: 100px;background-color: red;border-radius: 50px;border: 10px solid black;}</style>
</head>
<body><div></div><script>const div = document.querySelector('div')div.className = 'box'</script>
</body>
</html>
結果如下:
注意事項:
- 因
class
是關鍵字,故使用className
代替 className
會用新值替換舊值,若需添加類,需保留原有類名
通過 classList 操作類以控制 CSS
目的:為解決 className
易覆蓋原有類名的問題,可通過 classList
追加或刪除類名
語法:
- 追加類:
元素.classList.add('類名')
- 刪除類:
元素.classList.remove('類名')
- 切換類:
元素.classList.toggle('類名')
代碼示例:
<!DOCTYPE html>
<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: 200px;height: 200px;background-color: pink; text-align: center;}.first {width: 300px;height: 100px;}.second {background-color: red;border-radius: 50px;border: 10px solid black;}.third {font-size: 80px;}.forth {background-color: skyblue;/* 文字垂直居中 */line-height: 200px;}</style>
</head>
<body><div class="box">abcd</div><script>// 獲取元素const box = document.querySelector('.box')// 添加類名box.classList.add('first','second','third')// 刪除類名box.classList.remove('first')// 切換類名 —— 如果類名存在則刪除,不存在則添加box.classList.toggle('forth')</script>
</body>
</html>
結果如下:
案例:輪播圖(初級)
代碼示例:
<!DOCTYPE html>
<!-- 聲明 HTML 文檔的語言為英語 -->
<html lang="en">
<head><!-- 設置文檔的字符編碼為 UTF-8 --><meta charset="UTF-8"><!-- 配置頁面在不同設備上的視圖 --><meta name="viewport" content="width=device-width, initial-scale=1.0"><!-- 設置頁面的標題 --><title>Document</title><style>/* 全局設置,將所有元素的盒模型設置為 border-box */* {box-sizing: border-box;}/* 輪播圖容器樣式 */.slider {width: 280px;height: 400px;/* 隱藏超出容器的內容 */overflow: hidden;}/* 輪播圖圖片包裝器樣式 */.slider-wrapper {width: 100%;height: 320px;}/* 輪播圖圖片樣式 */.slider-wrapper img {width: 100%;height: 100%;/* 將圖片顯示為塊級元素 */display: block;}/* 輪播圖底部區域樣式 */.slider-footer {height: 80px;background-color: rgb(100, 67, 68);/* 設置內邊距,下、左、右內邊距為 12px */padding: 12px 12px 12px;/* 相對定位,為子元素的絕對定位提供參考 */position: relative;}/* 輪播圖切換按鈕容器樣式 */.slider-footer .toggle {/* 絕對定位,位于父元素的右上角 */position: absolute;right: 0;top: 12px;/* 使用 flex 布局 */display: flex;}/* 輪播圖切換按鈕樣式 */.slider-footer .toggle button {margin-right: 12px;width: 28px;height: 28px;/* 去除瀏覽器默認樣式 */appearance: none;border: none;background: rgba(255, 255, 255, 0.1);color: #fff;border-radius: 4px;/* 鼠標懸停時顯示指針樣式 */cursor: pointer;}/* 輪播圖切換按鈕懸停樣式 */.slider-footer .toggle button:hover {background: rgba(255, 255, 255, 0.2);}/* 輪播圖底部區域文字樣式 */.slider-footer p {margin: 0;color: #fff;font-size: 18px;margin-bottom: 10px;}/* 輪播圖指示器列表樣式 */.slider-indicator {margin: 0;padding: 0;/* 去除列表默認樣式 */list-style: none;/* 使用 flex 布局,垂直居中對齊 */display: flex;align-items: center;}/* 輪播圖指示器列表項樣式 */.slider-indicator li {width: 8px;height: 8px;margin: 4px;border-radius: 50%;background: #fff;/* 設置透明度 */opacity: 0.4;cursor: pointer;}/* 激活狀態的輪播圖指示器列表項樣式 */.slider-indicator li.active {width: 12px;height: 12px;/* 不透明 */opacity: 1;}</style>
</head>
<body><!-- 輪播圖容器 --><div class="slider"><!-- 輪播圖圖片包裝器 --><div class="slider-wrapper"><!-- 輪播圖初始圖片 --><img src="./img/1.png" alt=""></div><!-- 輪播圖底部區域 --><div class="slider-footer"><!-- 顯示輪播圖名稱的段落 --><p>假面騎士空我</p><!-- 輪播圖指示器列表 --><ul class="slider-indicator"><!-- 指示器列表項 --><li></li><li></li><li></li><li></li><li></li></ul><!-- 輪播圖切換按鈕容器 --><div class="toggle"><!-- 上一張圖片按鈕 --><button class="prev"><</button><!-- 下一張圖片按鈕 --><button class="next">></button></div></div></div><script>// 定義輪播圖數據數組,包含圖片路徑、名稱和對應的背景顏色let data = [{src:'./img/1.png',name:'假面騎士空我',color: 'rgb(100, 67, 68)'},{src:'./img/2.png',name:'假面騎士亞極陀',color: 'rgb(100, 67, 68)'},{src:'./img/3.png',name:'假面騎士龍騎',color: 'rgb(100, 67, 68)'},{src:'./img/4.png',name:'假面騎士555',color: 'rgb(100, 67, 68)'},{src:'./img/5.png',name:'假面騎士劍',color: 'rgb(100, 67, 68)'}]// 生成一個隨機數,用于隨機選擇輪播圖數據數組中的一項const random = Math.floor(Math.random() * data.length)// 獲取輪播圖圖片元素const img = document.querySelector('.slider-wrapper img')// 修改圖片的 src 屬性,顯示隨機選擇的圖片img.src = data[random].src// 獲取輪播圖底部區域的段落元素const p = document.querySelector('.slider-footer p')// 修改段落的內容,顯示隨機選擇的輪播圖名稱p.innerHTML = data[random].name// 獲取輪播圖底部區域元素const footer = document.querySelector('.slider-footer')// 修改底部區域的背景顏色,使用隨機選擇的顏色footer.style.backgroundColor = data[random].color// 獲取對應的輪播圖指示器列表項const li = document.querySelector(`.slider-indicator li:nth-child(${random + 1})`)// 為選中的指示器列表項添加 active 類,改變其樣式li.classList.add('active')</script>
</body>
</html>
結果如下:
屏幕錄制 2025-03-29 222527