当前位置: 首页 > article >正文

JavaScript web API part3

web API

DOM

日期对象

==> 得到当前系统的时间

new这个操作就是实例化

语法

const date = new Date() or const date = new Date('2004-11-3 08:00:00')

可以指定时间 ===> 可应用于通过系统时间和指定时间实现倒计时的操作

//得到当前时间
    const date = new Date()
    console.log(date);

    //指定时间
    const date1 = new Date('2024-5-5 08:30:00')
    console.log(date1);

方法

tolocaleString() tolocalDateString() tolocalTimeString()

方法作用
getFullYear()获取年份 四位的
getMonth()获取月份 0~11
getDate()获取月份中的每一天
getDay()获取星期 0~6
getHours()获取小时 0~23
getMinutes()获取分钟 0~59
getSeconds()获取秒 0~59

补充说明:

  • getDay()若要显示‘星期几’到页面上,需要配合数组存储响应的文字进行使用
  • getMonth()显示到页面时需要+1
 const date = new Date()
    // function myDate() {
    //   const date = new Date()
    //   let h = date.getHours()
    //   let m = date.getMinutes()
    //   let s = date.getSeconds()
    //   h = h < 10 ? '0' + h : h
    //   m = m < 10 ? '0' + m : m
    //   s = s < 10 ? '0' + s : s

    //   div.innerHTML = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()} ${h}:${m}:${s}`
    // }
    const div = document.querySelector('div')
    setInterval(function () {
      // myDate()

      // div.innerHTML = date.toLocaleString()
      // div.innerHTML = date.toLocaleDateString()
      // div.innerHTML = date.toLocaleTimeString()


    }, 1000)
    // let dayArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    // console.log(dayArr[date.getDay()]);
    // div.innerHTML = dayArr[date.getDay()]

时间戳

从1970年1/1 00:00::00至现在的毫秒数

可用于倒计时相减

[!IMPORTANT]

时间戳是时间对象用来相减运算的手段

获取方法

getTime() +new Date() Date.now()

setInterval(function () {
      //1.第一种方法
      // const date = new Date()
      // console.log(date.getTime()); //需实例化
      //2.第二种方法 
      // console.log(+new Date());

      //3.第三种方法
      const date = new Date()
      console.log(Date.now());

    }, 1000)

补充:

  • 前两个可以指定时间
  • 而第二个无需实例化,常用

案例

倒计时

在这里插入图片描述

<!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>
    .countdown {
      width: 240px;
      height: 305px;
      text-align: center;
      line-height: 1;
      color: #fff;
      background-color: brown;
      /* background-size: 240px; */
      /* float: left; */
      overflow: hidden;
    }

    .countdown .next {
      font-size: 16px;
      margin: 25px 0 14px;
    }

    .countdown .title {
      font-size: 33px;
    }

    .countdown .tips {
      margin-top: 80px;
      font-size: 23px;
    }

    .countdown small {
      font-size: 17px;
    }

    .countdown .clock {
      width: 142px;
      margin: 18px auto 0;
      overflow: hidden;
    }

    .countdown .clock span,
    .countdown .clock i {
      display: block;
      text-align: center;
      line-height: 34px;
      font-size: 23px;
      float: left;
    }

    .countdown .clock span {
      width: 34px;
      height: 34px;
      border-radius: 2px;
      background-color: #303430;
    }

    .countdown .clock i {
      width: 20px;
      font-style: normal;
    }
  </style>
</head>

<body>
  <div class="countdown">
    <p class="next">今天是2024年9月15日</p>
    <p class="title">秒杀倒计时</p>
    <p class="clock">
      <span id="hour">00</span>
      <i>:</i>
      <span id="minutes">25</span>
      <i>:</i>
      <span id="scond">20</span>
    </p>
    <p class="tips">18:30:00下课</p>
  </div>
  <script>
    // 随机颜色函数
    // 1. 自定义一个随机颜色函数
    function getRandomColor(flag = true) {
      if (flag) {
        // 3. 如果是true 则返回 #ffffff
        let str = '#'
        let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
        // 利用for循环随机抽6次 累加到 str里面
        for (let i = 1; i <= 6; i++) {
          // 每次要随机从数组里面抽取一个  
          // random 是数组的索引号 是随机的
          let random = Math.floor(Math.random() * arr.length)
          // str = str + arr[random]
          str += arr[random]
        }
        return str

      } else {
        // 4. 否则是 false 则返回 rgb(255,255,255)
        let r = Math.floor(Math.random() * 256)  // 55
        let g = Math.floor(Math.random() * 256)  // 89
        let b = Math.floor(Math.random() * 256)  // 255
        return `rgb(${r},${g},${b})`
      }

    }

    // 页面刷新随机得到颜色
    const countdown = document.querySelector('.countdown')
    countdown.style.backgroundColor = getRandomColor()
    // 函数封装 getCountTime
    function getCountTime() {
      // 1. 得到当前的时间戳
      const now = +new Date()
      // 2. 得到将来的时间戳
      const last = +new Date('2024-9-15 18:30:00')
      // console.log(now, last)
      // 3. 得到剩余的时间戳 count  记得转换为 秒数
      const count = (last - now) / 1000
      // console.log(count)
      // 4. 转换为时分秒
      // h = parseInt(总秒数 / 60 / 60 % 24)   //   计算小时
      // m = parseInt(总秒数 / 60 % 60);     //   计算分数
      // s = parseInt(总秒数 % 60);   
      // let d = parseInt(count / 60 / 60 / 24)               //   计算当前秒数
      let h = parseInt(count / 60 / 60 % 24)
      h = h < 10 ? '0' + h : h
      let m = parseInt(count / 60 % 60)
      m = m < 10 ? '0' + m : m
      let s = parseInt(count % 60)
      s = s < 10 ? '0' + s : s
      console.log(h, m, s)

      //  5. 把时分秒写到对应的盒子里面
      document.querySelector('#hour').innerHTML = h
      document.querySelector('#minutes').innerHTML = m
      document.querySelector('#scond').innerHTML = s
    }
    // 先调用一次 **
    getCountTime()

    // 开启定时器
    setInterval(getCountTime, 1000)
  </script>
</body>

</html>

在这里插入图片描述


节点操作

DOM节点

DOM树中每一个内容 —包括元素节点,属性节点,文本节点等等

父节点查找

子元素.parentNode ==> 找不到返回null

子节点查找

父元素.children ==> 找的是亲儿子 ==> 获取所有元素节点,返回伪数组

补充另一种方法:

childNode —了解即可

兄弟节点查找

兄弟元素.previousElementSibling(前一个) 兄弟元素.nextElementSibling(下一个)

<!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>
  <div class="dad">
    <div class="baby"></div>
  </div>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
  <script>
    const dad = document.querySelector('.dad')
    console.log(dad.children);

    const baby = document.querySelector('.baby')
    console.dir(baby.parentNode);


    const li1 = document.querySelector('ul li:nth-child(1)')
    console.log(li1.nextElementSibling);

    console.log(li1.nextElementSibling.previousElementSibling);


  </script>
</body>

</html>

案例

关闭广告操作改良版:

<!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>
    .box {
      position: relative;
      width: 1000px;
      height: 200px;
      background-color: pink;
      margin: 100px auto;
      text-align: center;
      font-size: 50px;
      line-height: 200px;
      font-weight: 700;
    }

    .box1 {
      position: absolute;
      right: 20px;
      top: 10px;
      width: 20px;
      height: 20px;
      background-color: skyblue;
      text-align: center;
      line-height: 20px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="box">
    我是广告
    <div class="box1">X</div>
  </div>
  <div class="box">
    我是广告
    <div class="box1">X</div>
  </div>
  <div class="box">
    我是广告
    <div class="box1">X</div>
  </div>
  <script>
    // // 1. 获取事件源
    // const box1 = document.querySelector('.box1')
    // // 2. 事件侦听
    // box1.addEventListener('click', function () {
    //   this.parentNode.style.display = 'none'
    // })

    // 1. 获取三个关闭按钮
    // const closeBtn = document.querySelectorAll('.box1')
    // for (let i = 0; i < closeBtn.length; i++) {
    //   closeBtn[i].addEventListener('click', function () {
    //     // 关闭我的爸爸 所以只关闭当前的父元素
    //     this.parentNode.style.display = 'none'
    //   })
    // }

    const closeBtn = document.querySelectorAll('.box1')
    for (let i = 0; i < closeBtn.length; i++) {
      closeBtn[i].addEventListener('click', function () {
        this.parentNode.style.display = 'none'
      })
    }    
  </script>
</body>

</html>

增加节点

==> 如发布信息的时候,需要增加元素

  1. 创建 document.creatElement('标签名')
  2. 插入
    1. 父元素最后一个子元素 父元素.appendchild(元素)
    2. 父元素中某个子元素的前面 父元素.insertBefore(插入的元素,在谁前面)
<!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>
  <ul>
    <li>first</li>
  </ul>
  <script>
    //1.创建节点
    const li = document.createElement('li')
    li.innerHTML = 'twice'
    //2.插入节点
    //2.1获取父元素节点
    const ul = document.querySelector('ul')
    //2.2插入新节点
    ul.appendChild(li)
    // ul.insertBefore(li, ul.children[0])
  </script>
</body>

</html>

案例

学生在线JavaScript方法重构

  1. 创建ul
  2. 创建相应个数的li
  3. 添加内容到li
  4. li追加到ul里
  // 1. 重构  
        let data = [
            {
                src: 'images/course01.png',
                title: 'Think PHP 5.0 博客系统实战项目演练',
                num: 1125
            },
            {
                src: 'images/course02.png',
                title: 'Android 网络动态图片加载实战',
                num: 357
            },
            {
                src: 'images/course03.png',
                title: 'Angular2 大前端商城实战项目演练',
                num: 22250
            },
            {
                src: 'images/course04.png',
                title: 'Android APP 实战项目演练',
                num: 389
            },
            {
                src: 'images/course05.png',
                title: 'UGUI 源码深度分析案例',
                num: 124
            },
            {
                src: 'images/course06.png',
                title: 'Kami2首页界面切换效果实战演练',
                num: 432
            },
            {
                src: 'images/course07.png',
                title: 'UNITY 从入门到精通实战案例',
                num: 888
            },
            {
                src: 'images/course08.png',
                title: 'Cocos 深度学习你不会错过的实战',
                num: 590
            },
        ]
        //获取父元素
        const ul = document.querySelector('.clearfix')

        for (let i = 0; i < data.length; i++) {
            //1.创建li
            const li = document.createElement('li')
            //2.追加li
            li.innerHTML = `
             <a href="#">
                    <img src=${data[i].src} alt="">
                    <h4>
                        ${data[i].title}
                    </h4>
                    <div class="info">
                        <span>高级</span> • <span>${data[i].num}</span>人在学习
                    </div>
                </a>
            `
            ul.appendChild(li)
        }

克隆节点

  1. 复制原有
  2. 引入指定元素

元素.cloneNode(布尔值)

布尔值为真,克隆则包含后代节点以及相应的内容

布尔值为假,就仅仅只是包含标签是什么的内容

删除节点

通过父元素进行删除

父元素.removechild(删除元素对象)

 //1.复制原有
    const li = document.querySelector('ul li:nth-child(1)').cloneNode(true)
    //2.放入ul中
    //获取父元素对象
    const ul = document.querySelector('ul')
    ul.appendChild(li)
    
     //1.获取父元素对象
    const ul = document.querySelector('ul')
    //2.删除父元素所在的树杈的节点
    ul.removeChild(ul.children[0])

综合案例

==> 学生信息表上传
在这里插入图片描述
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>学生信息管理</title>
  <link rel="stylesheet" href="css/index.css" />
</head>

<body>
  <h1>新增学员</h1>
  <form class="info" autocomplete="off">
    姓名:<input type="text" class="uname" name="uname" />
    年龄:<input type="text" class="age" name="age" />
    性别:
    <select name="gender" class="gender">
      <option value=""></option>
      <option value=""></option>
    </select>
    薪资:<input type="text" class="salary" name="salary" />
    就业城市:<select name="city" class="city">
      <option value="北京">北京</option>
      <option value="上海">上海</option>
      <option value="广州">广州</option>
      <option value="深圳">深圳</option>
      <option value="曹县">曹县</option>
    </select>
    <button class="add">录入</button>
  </form>

  <h1>就业榜</h1>
  <table>
    <thead>
      <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>薪资</th>
        <th>就业城市</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>



    </tbody>
  </table>
  <script>
    //获取元素
    const uname = document.querySelector('.uname')
    const gender = document.querySelector('.gender')
    const salary = document.querySelector('.salary')
    const city = document.querySelector('.city')
    const age = document.querySelector('.age')
    const tbody = document.querySelector('tbody')
    //获取所有带name属性的元素
    const items = document.querySelectorAll('[name]')
    //添加空数组
    let arr = []
    //1.点击模块
    //1.1表单提交事件
    const info = document.querySelector('.info')
    info.addEventListener('submit', function (e) {
      //阻止默认行为 不跳转
      e.preventDefault()
      //这里进行表单的验证
      for (let i = 0; i < items.length; i++) {
        if (items[i].value === '') {
          return alert('输入内容不能为空')
        }
      }
      //创建新的对象 并存入表单数据
      const obj = {
        stuid: arr.length + 1,
        uname: uname.value,
        age: age.value,
        gender: gender.value,
        salary: salary.value,
        city: city.value

      }
      // console.log(obj);
      //追加到数组中
      arr.push(obj)
      // console.log(arr);
      //清空表单数据
      this.reset()
      render()
    })
    // 渲染函数
    function render() {
      //先清空tbody中的数据
      tbody.innerHTML = ''
      //遍历arr数组
      for (let i = 0; i < arr.length; i++) {
        //生成tr
        const tr = document.createElement('tr')
        tr.innerHTML =        ` 
        <td>${arr[i].stuid}</td>
        <td>${arr[i].uname}</td>
        <td>${arr[i].age}</td>
        <td>${arr[i].gender}</td>
        <td>${arr[i].salary}</td>
        <td>${arr[i].city}</td>
        <td>
          <a href="javascript:" data-id=${arr[i].stuid} >删除</a>
        </td>      
        //追加到tbody中
        tbody.appendChild(tr)
        `   
      }
    }
    //3.删除操作
    //3.1事件委托到tbody
    tbody.addEventListener('click', function (e) {
      if (e.target.tagName === 'A') {
        // console.log(e.target.dateset);
        arr.splice(+(e.target.dateset), 1)
        //重新渲染表格
        render()
      }
    })
  </script>
</body>
</html>

在这里插入图片描述

M端事件

移动端才会发生的事件(了解常用)

在这里插入图片描述

JS插件

swiper

在这里插入图片描述


http://www.kler.cn/news/305674.html

相关文章:

  • PCIe进阶之TL:Address Spaces, Transaction Types, and Usage
  • Java多线程1
  • Android13 Launcher3屏蔽桌面指示器
  • 外包干了半年,快要废了。。。
  • 【c++】类和对象详解
  • React18快速入门
  • 切换淘宝最新镜像源npm
  • VSCode学习笔记
  • Linux开发讲课44---linux性能查看命令和工具
  • 在职研生活学习--20240907
  • FaaS(Function as a Service)框架集成springboot
  • 【数据结构-一维差分】力扣2848. 与车相交的点
  • MySQL 8.0授权语法变更及解决方案‌
  • 点云深度学习系列:Sam2Point——基于提示的点云分割
  • 2024上半年国产操作系统卖疯了!麒麟4.9亿,统信1.9亿!
  • 架构设计:负责网络、定时、坐下、站起、重连等,支持多类游戏的无锁房间
  • Oracle发送邮件功能:配置自动化发信指南?
  • Redis搭建集成
  • 【ACM独立出版】第二届物联网与云计算技术国际学术会议 (IoTCCT 2024,9月27-29)
  • BookStack在线文档管理系统本地Docker部署与远程访问详细教程
  • 安全运维工程师学习路线
  • Unity实现自己的协程系统
  • RFB_modified模块的作用?和ASPP模块的区别?
  • GLSL 棋盘shader
  • STM32 HAL freertos零基础(六)计数型信号量
  • 十二,Spring Boot 异常处理(自定义异常页面,全局异常,自定义异常)
  • 视频融合共享平台LntonAIServer视频分析平台噪声监测优势
  • 【计算机网络 - 基础问题】每日 3 题(五)
  • 【数据结构】8——图3,十字链表,邻接多重表
  • Android Activity组件与进程启动间关系