您的位置:首页 > 娱乐 > 明星 > JavaScript web API part3

JavaScript web API part3

2024/10/7 4:32:09 来源:https://blog.csdn.net/wozhaonue_w/article/details/142290086  浏览:    关键词: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 则返回 #fffffflet 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)  // 55let g = Math.floor(Math.random() * 256)  // 89let b = Math.floor(Math.random() * 256)  // 255return `rgb(${r},${g},${b})`}}// 页面刷新随机得到颜色const countdown = document.querySelector('.countdown')countdown.style.backgroundColor = getRandomColor()// 函数封装 getCountTimefunction 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 : hlet m = parseInt(count / 60 % 60)m = m < 10 ? '0' + m : mlet s = parseInt(count % 60)s = s < 10 ? '0' + s : sconsole.log(h, m, s)//  5. 把时分秒写到对应的盒子里面document.querySelector('#hour').innerHTML = hdocument.querySelector('#minutes').innerHTML = mdocument.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.创建liconst li = document.createElement('li')//2.追加lili.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++) {//生成trconst 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事件委托到tbodytbody.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

在这里插入图片描述

版权声明:

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

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