一、日期对象
1.1 实例化
目标:能够实例化日期对象
- 在代码中发现了 new 关键字时,一般将这个操作称为实例化
- 创建一个时间对象并获取时间
<body>
<script>
// 实例化 new
// 1.得到当前时间
const date = new Date()
console.log(date)
// 2.指定时间
const date1 = new Date('2023-7-1 08:30:00')
console.log(date1)
</script>
</body>
1.2 日期对象方法
目标:能够使用日期对象中的方法写出常见日期
使用场景:因为日期对象返回的数据我们不能直接使用,所以需要转换为实际开发中常用的格式
<body>
<script>
// 获得日期对象
const date = new Date()
// 使用里面的方法
console.log(date.getFullYear())
console.log(date.getMonth()+1)
</script>
</body>
案例:页面显示时间
需求:将当前时间以:YYYY-MM-DD HH:mm 形式显示在页面 2008-08-08 08:08
案例分析:
①:调用日期对象方法进行转换
②:记得数字要补0
③:字符串拼接后,通过 innerText 给 标签
<style>
div{
width: 300px;
height: 40px;
border: 1px solid pink;
text-align: center;
line-height: 40px;
}
</style>
</head>
<body>
<div></div>
<script>
const div = document.querySelector('div')
function getMyDate() {
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
return `今天是:${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${h}:${m}:${s}`
}
div.innerHTML = getMyDate()
setInterval(function(){
div.innerHTML = getMyDate()
},1000)
</script>
</body>
时间的另一种方法(简单)
<body>
<div></div>
<script>
const div = document.querySelector('div')
// 得到日期对象
const date = new Date()
div.innerHTML = date.toLocaleString() //2023/6/23 11:47:04
// div.innerHTML = date.toLocaleDateString() //2023/6/23
// div.innerHTML = date.toLocaleTimeString() //11:49:14
setInterval(function(){
const date = new Date()
div.innerHTML = date.toLocaleString()
},1000)
</script>
</body>
1.3 时间戳
目标:能够获得当前时间戳
- 使用场景: 如果计算倒计时效果,前面方法无法直接计算,需要借助于时间戳完成
- 什么是时间戳:
是指1970年01月01日00时00分00秒起至现在的毫秒数,它是一种特殊的计量时间的方式 - 算法:
将来的时间戳 - 现在的时间戳 = 剩余时间毫秒数
剩余时间毫秒数 转换为 剩余时间的 年月日时分秒 就是 倒计时时间
比如 将来时间戳 2000ms - 现在时间戳 1000ms = 1000ms
1000ms 转换为就是 0小时0分1秒
得到指定时间的时间戳
<script>
console.log(+new Date('2023-6-1 18:00:00'))
</script>
// 我要根据日期Day() 0~6 返回的是 星期一
const arr = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六',]
console.log(arr[new Date().getDay()])
1.4 案例毕业倒计时效果
需求:计算到下课还有多少时间
案例分析:
①:用将来时间减去现在时间就是剩余的时间
②:核心: 使用将来的时间戳减去现在的时间戳
③:把剩余的时间转换为 天 时 分 秒
注意:
- 通过时间戳得到是毫秒,需要转换为秒在计算
- 转换公式:
d = parseInt(总秒数/ 60/60 /24); // 计算天数
h = parseInt(总秒数/ 60/60 %24) // 计算小时
m = parseInt(总秒数 /60 %60 ); // 计算分数
s = parseInt(总秒数%60); // 计算当前秒数
<!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">今天是2222年6月1日</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>
// 获得今天时间的标签
const next = document.querySelector('.next')
// 写今天的时间函数
function today() {
const date = new Date()
return `今天是${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日`
}
// console.log(today())
next.innerHTML = today()
// 随机颜色函数
// 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('2023-6-23 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 d = parseInt(count/60/60/24)
d = d < 10 ? '0' + d : d
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(d,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>
二、节点操作
2.1 DOM节点
目标:能说出DOM节点的类型
- DOM节点
DOM树里每一个内容都称之为节点 - 节点类型
(1)元素节点
所有的标签 比如 body、 div
html 是根节点
(2)属性节点
所有的属性 比如 href
(3)文本节点
所有的文本
(4)其他
2.2 查找节点
目标:能够具备根据节点关系查找目标节点的能力
- 关闭二维码案例:
点击关闭按钮, 关闭的是二维码的盒子, 还要获取erweima盒子 - 思考:
关闭按钮 和 erweima 是什么关系呢?
父子关系
所以,我们完全可以这样做:
点击关闭按钮, 直接关闭它的爸爸,就无需获取erweima元素了 - 节点关系:针对的找亲戚返回的都是对象
父节点
子节点
兄弟节点
2.2.1 父节点查找:
parentNode 属性
返回最近一级的父节点 找不到返回为null
<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'
})
}
</script>
2.2.2 子节点查找:
- childNodes
获得所有子节点、包括文本节点(空格、换行)、注释节点等 - children 属性 (重点)
仅获得所有元素节点
返回的还是一个伪数组
2.2.3 兄弟关系查找:
- 下一个兄弟节点
nextElementSibling 属性 - 上一个兄弟节点
previousElementSibling 属性
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
// const ul = document.querySelector('ul')
// console.log(ul.children) //得到伪数组 选择的是 亲儿子
const li2 = document.querySelector('ul li:nth-child(2)')
console.log(li2.previousElementSibling) //上一个兄弟
console.log(li2.nextElementSibling) //下一个兄弟
</script>
</body>
2.3 增加节点
目标:能够具备根据需求新增节点的能力
- 很多情况下,我们需要在页面中增加元素
比如,点击发布按钮,可以新增一条信息 - 一般情况下,我们新增节点,按照如下操作:
创建一个新的节点
把创建的新的节点放入到指定的元素内部 - 学习路线:
创建节点
追加节点
2.3.1 创建节点
- 即创造出一个新的网页元素,再添加到网页内,一般先创建节点,然后插入节点
- 创建元素节点方法:
2.3.2 追加节点
要想在界面看到,还得插入到某个父元素中
-
插入到父元素的最后一个子元素:
-
插入到父元素中某个子元素的前面
<body>
<ul>
<li>我是老大</li>
</ul>
<script>
// // 1.创建节点
// const div = document.createElement('div')
// console.log(div)
// // 2.追加节点 作为最后一个子元素
// document.body.appendChild(div)
const ul = document.querySelector('ul')
const li = document.createElement('li')
li.innerHTML = '我是li'
// ul.appendChild(li)
// 3.追加节点
ul.insertBefore(li, ul.children[0])
</script>
</body>
2.3.3 案例:学成在线案例渲染
分析:
①:准备好空的ul 结构
②:根据数据的个数,创建一个新的空li
③:li里面添加内容 img 标题等
④:追加给ul
重点练习:创建节点和追加节点
<body>
<!-- 4. box核心内容区域开始 -->
<div class="box w">
<div class="box-hd">
<h3>精品推荐</h3>
<a href="#">查看全部</a>
</div>
<div class="box-bd">
<ul class="clearfix">
</ul>
</div>
</div>
<script>
// 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('.box-bd ul')
// 1. 根据数据的个数,创建 对应的小li
for (let i = 0; i < data.length; i++) {
// 2. 创建新的小li
const li = document.createElement('li')
// 把内容给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>
`
// 3. ul追加小li
ul.appendChild(li)
}
</script>
</body>
2.4 克隆节点
- 特殊情况下,我们新增节点,按照如下操作:
复制一个原有的节点
把复制的节点放入到指定的元素内部 - 克隆节点
cloneNode会克隆出一个跟原标签一样的元素,括号内传入布尔值
若为true,则代表克隆时会包含后代节点一起克隆
若为false,则代表克隆时不包含后代节点
默认为false
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
const ul = document.querySelector('ul')
// 1.克隆节点 元素.cloneNode(true)
const li1 = ul.children[0].cloneNode(true)
// console.log(li1)
// 2.追加
// ul.appendChild(li1)
ul.appendChild(ul.children[0].cloneNode(true))
</script>
</body>
2.5 删除节点
目标:能够具备根据需求删除节点的能力
- 若一个节点在页面中已不需要时,可以删除它
- 在 JavaScript 原生DOM操作中,要删除元素必须通过父元素删除
- 语法
- 注:
如不存在父子关系则删除不成功
删除节点和隐藏节点(display:none) 有区别的: 隐藏节点还是存在的,但是删除,则从html中删除节点
<body>
<ul>
<li>没用了</li>
</ul>
<script>
const ul = document.querySelector('ul')
// 删除节点 父元素.removeChild(子元素)
ul.removeChild(ul.children[0])
</script>
</body>
三、M端事件
目标:了解M端常见的事件
移动端也有自己独特的地方。比如触屏事件 touch(也称触摸事件),Android 和 IOS 都有。
- 触屏事件 touch(也称触摸事件),Android 和 IOS 都有。
- touch 对象代表一个触摸点。触摸点可能是一根手指,也可能是一根触摸笔。触屏事件可响应用户手指(或触控笔)对屏幕或者触控板操作。
- 常见的触屏事件如下:
<style>
div{width: 300px;
height: 300px;
background-color:pink;}
</style>
</head>
<body>
<div></div>
<script>
const div = document.querySelector('div')
// 1.触摸
div.addEventListener('touchstart', function() {
console.log('开始摸我')
})
// 2.离开
div.addEventListener('touchend', function() {
console.log('离开了')
})
// 3.移动
div.addEventListener('touchmove', function() {
console.log('一直摸,移动')
})
</script>
</body>
四、JS插件(轮播图幻灯片)
- 插件: 就是别人写好的一些代码,我们只需要复制对应的代码,就可以直接实现对应的效果
- 学习插件的基本过程
熟悉官网,了解这个插件可以完成什么需求 https://www.swiper.com.cn/
看在线演示,找到符合自己需求的demo https://www.swiper.com.cn/demo/index.html
查看基本使用流程 https://www.swiper.com.cn/usage/index.html
查看APi文档,去配置自己的插件 https://www.swiper.com.cn/api/index.html
注意: 多个swiper同时使用的时候, 类名需要注意区分
<!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="stylesheet" href="./css/swiper.min.css">
<style>
.box{
position: relative;
margin: 100px auto;
width: 800px;
height: 300px;
background-color: pink;
}
html,
body {
position: relative;
height: 100%;
}
body {
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: 0;
padding: 0;
}
.swiper {
overflow: hidden;
width: 100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
</head>
<body>
<div class="box">
<!-- Swiper -->
<div class="swiper mySwiper">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
<div class="swiper-slide">Slide 5</div>
<div class="swiper-slide">Slide 6</div>
<div class="swiper-slide">Slide 7</div>
<div class="swiper-slide">Slide 8</div>
<div class="swiper-slide">Slide 9</div>
</div>
<div class="swiper-pagination"></div>
</div>
</div>
<script src="./js/swiper.min.js"></script>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper(".mySwiper", {
pagination: {
el: ".swiper-pagination",
},
//自动播放
autoplay: {
delay: 1000,//1秒切换一次
disableOnInteraction: false, //鼠标触摸之后继续自动播放
},
// 用键盘控制
keyboard: {
enabled: true,
onlyInViewport: true,
},
});
</script>
</body>
</html>
五、综合案例
1.游乐园轮播图
2.学生信息表案例
核心思路:
①: 声明一个空的数组
②: 点击录入,根据相关数据,生成对象,追加到数组里面
③: 根据数组数据渲染页面-表格的 行
④: 点击删除按钮,删除的是对应数组里面的数据
⑤: 再次根据数组的数据,渲染页面
业务模块:
①: 点击录入按钮可以录入数据
②: 点击删除可以删除当前的数据
说明:
本次案例,我们尽量减少dom操作,采取操作数据的形式
增加和删除都是针对于数组的操作,然后根据数组数据渲染页面
核心思路:
①: 声明一个空的数组
②: 点击录入模块
(1). 首先取消表单默认提交事件
(2). 创建新的对象,里面存储 表单获取过来的数据,格式如右图
(3). 追加给数组
(4). 渲染数据。 遍历数组, 动态生成tr, 里面填写对应td数据, 并追加给 tbody
(5). 重置表单
(6). 注意防止多次生成多条数据,先清空 tbody
③: 点击删除模块
(1). 采用事件委托形式,给 tbody 注册点击事件
(2). 点击链接,要删除的是对应数组里面的这个数据,而不是删除dom节点,如何找到这个数据?
(3). 前面渲染数据的时候,动态给a链接添加 自定义属性 data-id=“0”,这样点击当前对象就知道索引号了
(4). 根据索引号,利用 splice 删除这条数据
(5). 重新渲染
④: 点击新增需要验证表单
(1). 获取所有需要填写的表单, 他们共同特点都有 name属性
(2). 遍历这些表单,如果有一个值为空,则return 返回提示输入为空中断程序
(3). 注意书写的位置,应该放到新增数据的前面, 阻止默认行为的后面
<!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>
<!-- autocomplete="off" 关闭之前的录入信息 -->
<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>
<!-- <tr>
<td>1001</td>
<td>欧阳霸天</td>
<td>19</td>
<td>男</td>
<td>15000</td>
<td>上海</td>
<td>
<a href="javascript:">删除</a>
</td>
</tr> -->
</tbody>
</table>
<script>
// 获取元素
const uname = document.querySelector('.uname')
const age = document.querySelector('.age')
const gender = document.querySelector('.gender')
const salary = document.querySelector('.salary')
const city = document.querySelector('.city')
const tbody = document.querySelector('tbody')
// 获取所有带有name属性的元素
const items = document.querySelectorAll(['[name]'])
// 声明一个空的数组,增加和删除都是对这个数组进行操作
const arr = []
// 1.录入模块
// 1.1 表单提交事件
const info = document.querySelector('.info')
info.addEventListener('submit', function(e) {
// 阻止默认行为 不跳转
e.preventDefault()
// console.log(11)
// 这里进行表单验证,如果不通过,直接中段,不需要添加数据
// 先遍历循环
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()
})
// 2.渲染函数 因为增加和删除都需要渲染
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 = ${i}>删除</a>
</td>
`
// 追加元素 父元素.appendChild(子元素)
tbody.appendChild(tr)
}
}
// 3.删除操作
// 3.1 事件委托 tbody
tbody.addEventListener('click', function(e){
if (e.target.tagName === 'A') {
// alert(11)
// 得到当前元素的自定义属性 data-Id
// console.log(e.target.dataset.id)
// 删除arr 数组里面对应的数据
arr.splice(e.target.dataset.id,1)
console.log(arr)
// 重新渲染一次
render()
}
})
</script>
</body>
</html>
用javascript:;替代 # 则不会出现点击了超链接后页面跳到页顶部的问题