DOM对象(pink老师课程笔记)

发布时间 2023-11-16 16:55:14作者: 齐嘉树

let or const

  • const优先
  • 对于引用数据类型,const存储的是地址
  • 数组和对象使用const声明

作用和分类

作用:使用JS去操作html和浏览器

分类:DOM(文档对象模型)和BOM(浏览器对象模型)

DOM

操作网页内容(标签)

DOM树

将HTML文档以树状结构表现出来,直观体现标签与标签之间的关系

DOM对象

浏览器根据html标签生成的JS对象

修改对象的属性会自动映射到标签中

document对象——html中最大的对象

获取DOM元素

两种方式:推荐CSS选择器的方式获取DOM元素,必须是字符串

选择匹配的第一个元素

document.querySelector('css选择器')

<div class="box"></div>
    <p id="nav"></p>
    <ul>
        <li>test</li>
        <li></li>
        <li></li>
    </ul>
    <script>
        // const box = document.querySelector('div')
        const box = document.querySelector('.box')
        const nav = document.querySelector('#nav')
        console.log(box)
        console.log(nav)
        // 获取第一个li
        const li = document.querySelector('ul li:first-child')
        console.log(li)
    </script>

返回的是第一个元素,一个html对象

选择匹配的所有元素

document.querySelectorAll('css选择器')

const lis = document.querySelectorAll('ul li')
        console.log(lis)

返回的是一个Nodelist对象集合

得到的是一个伪数组

  • 有长度有索引的数组
  • 没有pop() push()等方法
  • 需要经过遍历得到里面的每一个对象
<ul class="nav">
        <li>我的首页</li>
        <li>产品介绍</li>
        <li>联系方式</li>
    </ul>
    <script>
        // 获取元素
        const lis = document.querySelectorAll('.nav li')
        console.log(lis)
        // 打印每一个元素
        for (let i = 0; i < lis.length; i++) {
            console.log(lis[i])

        }

操作元素内容-修改元素的文本更换内容

对象.innerText属性

  1. 将文本添加到任意标签位置
  2. 显示纯文本不解析标签
<div class="box">我是文字内容</div>
    <script>
        // 获取元素
        const box = document.querySelector('.box')
        // 修改文字内容
        console.log(box.innerText)  //获取文字内容
        box.innerText = '我是一个盒子'//修改文字内容

对象.innerHTNL属性

  1. 将文本添加到任意标签位置
  2. 解析标签,多标签建议使用模板字符
 box.innerHTML = '<strong>我是一个盒子</strong>'//修改文字内容

随机抽奖

<div class="wrapper">
    <strong>传智教育年会抽奖</strong>
    <h1>一等奖:<span id="one">???</span></h1>
    <h3>二等奖:<span id="two">???</span></h3>
    <h5>三等奖:<span id="three">???</span></h5>
  </div>
  <script>
    // 声明数组
    const personArr = ['小周', '小田', '小白', '小朱', '小王']
    // 一等奖
    // 随机数——数组下标
    const random = Math.floor(Math.random() * personArr.length)
    // 获取元素
    const one = document.querySelector('h1 #one')
    // 把名字给one
    one.innerHTML = personArr[random]
    // 删除数组这个名字
    personArr.splice(random, 1)

操作元素属性

常用属性

对象.属性=值

href title src

<img src="./images/1.webp" alt="">

    <script>
        // 获取
        const img = document.querySelector('img')
        // 修改属性 对象.属性=值
        img.src = './images/2.webp'
        img.title = 'photo'
<img src="./images/1.webp" alt="">

    <script>
        // 取随机数
        function getRandom(N, M) {
            return Math.floor(Math.random() * (M - N + 1))
        }
        const random = getRandom(1, 6)
        // 获取
        const img = document.querySelector('img')
        // 修改属性 对象.属性=值
        img.src = `./images/${random}.webp`
        img.title = 'photo'

样式属性

  1. 通过style属性控制样式
  2. 通过className属性控制样式
  3. 通过classList属性控制样式

style属性

对象.style.样式属性=值

<div class="box"></div>

    <script>
        const box = document.querySelector('.box')
        // 注意单位
        box.style.width = '300px'
        // 多组单词的采取小驼峰命名
        box.style.backgroundColor = 'green'
        box.style.border = '4px solid black'
        box.style.borderTop = '4px solid red'
  • 单位200px
  • 小驼峰backgroundColor

页面刷新更换背景图片

  1. 随机数
  2. background-image
  3. 标签选择body,可直接写document.body.style

className属性

元素.className='active'

<style>
        div {
            width: 200px;
            height: 200px;
            background-color: orange;
        }

        .box {
            width: 300px;
            height: 300px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <div></div>

    <script>
        const div = document.querySelector('div')
        div.className = 'box'
        
     </script>
</body>
  • 覆盖原来类名——解决方法:加上原来的类名
  • 缺点:多个类名操作麻烦

classList属性(常用)

追加或删除类名

元素.classList.add('active')

 <style>
        .box {
            width: 300px;
            height: 300px;
            color: black;
        }

        .active {
            color: aqua;
            background-color: orange;
            border: 2px solid blue;
        }
    </style>
</head>

<body>
    <div class="box">hi</div>

    <script>
        const box = document.querySelector('.box')
        //追加  add()类名不加点,并且是字符串
        box.classList.add('active')
        // 删除   remove()
        box.classList.remove('box')
        // 切换 toggle() 有则删掉,无则加上
        box.classList.toggle('box')
  1. 字符串
  2. add()
  3. remove()
  4. toggle()
  5. 不替换以前的类名

随机轮播图

<!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>轮播图点击切换</title>
  <style>
    * {
      box-sizing: border-box;
    }

    .slider {
      width: 560px;
      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);
      padding: 12px 12px 0 12px;
      position: relative;
    }

    .slider-footer .toggle {
      position: absolute;
      right: 0;
      top: 12px;
      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;
      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="./images/slider01.jpg" alt="" />
    </div>
    <div class="slider-footer">
      <p>对人类来说会不会太超前了?</p>
      <ul class="slider-indicator">
        <li></li>
        <li></li>
        <li></li>
        <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>
    // 1. 初始数据
    const sliderData = [
      { url: './images/slider01.jpg', title: '对人类来说会不会太超前了?', color: 'rgb(100, 67, 68)' },
      { url: './images/slider02.jpg', title: '开启剑与雪的黑暗传说!', color: 'rgb(43, 35, 26)' },
      { url: './images/slider03.jpg', title: '真正的jo厨出现了!', color: 'rgb(36, 31, 33)' },
      { url: './images/slider04.jpg', title: '李玉刚:让世界通过B站看到东方大国文化', color: 'rgb(139, 98, 66)' },
      { url: './images/slider05.jpg', title: '快来分享你的寒假日常吧~', color: 'rgb(67, 90, 92)' },
      { url: './images/slider06.jpg', title: '哔哩哔哩小年YEAH', color: 'rgb(166, 131, 143)' },
      { url: './images/slider07.jpg', title: '一站式解决你的电脑配置问题!!!', color: 'rgb(53, 29, 25)' },
      { url: './images/slider08.jpg', title: '谁不想和小猫咪贴贴呢!', color: 'rgb(99, 72, 114)' },
    ]
    const random = parseInt(Math.random() * sliderData.length)
    console.log(sliderData[random])
    // 修改背景
    const bg = document.querySelector('.slider-wrapper img')
    bg.src = sliderData[random].url
    // 修改ititle
    const p = document.querySelector('.slider-footer p')
    p.innerHTML = sliderData[random].title
    // 修改背景色
    const color = document.querySelector('.slider-footer')
    color.style.backgroundColor = sliderData[random].color
    // 修改小圆点
    const li = document.querySelectorAll('.slider-indicator li')
    li[random].classList.add('active')


  </script>
</body>

</html>
  • 小圆点——active

  • .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;
        }
    
  • opacity——不透明度

  • 修改背景图片——常用属性

  • 修改title——innerHTML

  • 修改背景颜色——style属性(小驼峰)

  • 修改小圆点——classList

表单元素属性

比如点击眼睛,可以看到密码

  • 获取: DOM对象.属性名

  • 设置: DOM对象.属性名 = 新值

<input type="text" value="电脑">

    <script>
        const uname=document.querySelector('input')
        // 获取表单里面的值
        console.log(uname.value)
        // 修改为看不见
        uname.type = 'password'
  • innerHTML获取不到表单的内容

disabled、checked、selected——使用布尔值(true 或false)

<input type="checkbox" name="" id="">
    <button>点击</button>

    <script>
        // 勾选复选框
        const ipt = document.querySelector('input')
        ipt.checked = true
        // 禁用按钮
        const btn = document.querySelector('button')
        btn.disabled = true

自定义属性

标准属性 :

标签天生自带的属性 比如class id title等, 可以直接使用点语法操作比如: disabled、checked、selected

自定义 属性:

  • 在html5中推出来了专门的data-自定义属性
  • 在标签上一律以data-开头
  • 在DOM对象上一律以dataset对象方式获取
<div data-id="1" data-spm="know">1</div>
    <div data-id="2">2</div>
    <div data-id="3">3</div>
    <div data-id="4">4</div>
    <div data-id="5">5</div>

    <script>
        const one = document.querySelector('div')
        console.log(one.dataset)   // DOMStringMap { id: '1', spm: 'know' }
        console.log(one.dataset.id)// 1
        console.log(one.dataset.spm)// know

定时器-间歇函数

每隔一段时间需要自动执行一段代码,不需要我们手动去触发

开启定时器

两种写法

// setInterval(函数,间隔时间)  1s等于1000ms
        setInterval(function () {
            console.log('一秒执行一次')
        }, 1000)
function fn() {
            console.log('一秒执行一次')
        }
        // 每隔1s调用一次fn函数
        setInterval(fn, 1000)
  1. 函数名字 不需要加括号
  2. 定时器返回的是一个 id

关闭定时器

/* let 变量名=setInterval(函数,间隔时间)
   clearInterval(变量名) */
   let n = setInterval(function () {
       console.log('你好')
   }, 1000)
   clearInterval(n)

用户注册倒计时

<textarea name="" id="" cols="30" rows="10">
        用户注册协议
        哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈
    </textarea>
    <br>
    <button class="btn" disabled>我已阅读该协议(60)</button>

    <script>
        const btn = document.querySelector('.btn')
        // 倒计时
        let i = 60
        // 开启定时器
        let b = setInterval(function () {
            i--
            btn.innerHTML = `我已阅读该协议(${i})`
            if (i === 0) {
                clearInterval(b)
                // 定时器停了,开启按钮
                btn.disabled = false
                btn.innerHTML = '同意'
            }
        }, 1000)

轮播图定时版

// 获取元素
        const bg = document.querySelector('.slider-wrapper img')
        const p = document.querySelector('.slider-footer p')
        const color = document.querySelector('.slider-footer')
        // 信号量  控制图片的张数
        let i = 0
        // 开启定时器
        setInterval(function () {
            i++
            // 无缝衔接位置
            if (i >= sliderData.length) {
                i = 0
            }
            bg.src = sliderData[i].url
            p.innerHTML = sliderData[i].title
            color.style.backgroundColor = sliderData[i].color
            // 小圆点
            // 删除之前的active
            document.querySelector('.slider-indicator .active').classList.remove('active')
            // 当前li添加active
            document.querySelector(`.slider-indicator li:nth-child(${i + 1})`).classList.add('active')
        }, 1000)