欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > 【JavaScript】合体期功法——DOM(一)

【JavaScript】合体期功法——DOM(一)

2025/4/1 23:34:26 来源:https://blog.csdn.net/m0_72516377/article/details/146715827  浏览:    关键词:【JavaScript】合体期功法——DOM(一)

目录

  • 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 更换图片。

常见属性:hreftitlesrc 等。

语法:对象.属性 = 值

代码示例:

<!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">&lt;</button><!-- 下一张图片按钮 --><button class="next">&gt;</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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词