日期对象
实例化
<script>
// 1. 得到当前日期对象
const date0 = new Date()
console.log(date0);
// 2. 得到指定日期对象
const date1 = new Date('2024-1-1 08:30:00')
console.log(date1);
</script>
日期对象方法
方法 | 作用 | 说明 |
---|---|---|
getFullYear() | 获取年份 | 获取四位数的年份信息 |
getMonth() | 获取月份 | 取值为 0 ~ 11 |
getDate() | 获取月份中的每一天 | 不同月份取值也不相同 |
getDay() | 获取星期 | 取值为 0 ~ 6 |
getHours() | 获取小时 | 取值为 0 ~ 23 |
getMinutes() | 获取分钟 | 取值为 0 ~ 59 |
getSeconds() | 获取秒 | 取值为 0 ~ 59 |
<script>
// 得到当前日期对象
const date = new Date()
// 使用对象的方法
console.log(date.getFullYear());
</script>
时间戳
获得时间戳的三种方式
- 方式一
<script>
// 得到当前日期对象
const date = new Date()
// 转化为当前日期所对应的时间戳
console.log(date.getTime())
</script>
- 方式二(推荐)
<script>
// 输出当前时间所对应的时间戳
console.log(+new Date())
// 输出指定时间所对应的时间戳
console.log(+new Date('2024-1-1 15:30:00'))
</script>
- 方式三
<script>
// 输出当前时间所对应的时间戳
console.log(Date.now())
</script>
实现倒计时案例
<body>
<div style="width: 300px; height: 180px; background-color: rgba(220, 226, 241, 0.8); margin: 0 auto; text-align: center; border-radius: 50%;">
<h2 style="margin: 10px; font-size: 30px;">倒计时</h2>
<p>
<span>距离</span>
<span id="dl"><strong>0000-0-0 00:00:00</strong></span>
<span>还剩</span>
</p>
<p style="font-size: 20px;">
<span id="d">00</span>
<strong>天</strong>
<span id="h">00</span>
<strong>时</strong>
<span id="m">00</span>
<strong>分</strong>
<span id="s">00</span>
<strong>秒</strong>
</p>
</div>
<script>
// 函数说明:
// 参数=截止日期的时间戳
// 返回值=false或者带有倒计时信息的数组
function getCountdown(deadline = +new Date() + (86400 * 1000)) {
// 获取当前日期
const current = +new Date()
// 设定终点日期
const dl = deadline
// 计算两者的差值(时间戳形式)
const count = (dl - current) / 1000 // 1ms 转为 1s 需要除以 1000
if (count < 0) return false
// 将时间戳进行拆分与整理
let day = parseInt(count / 60 / 60 / 24)
day = (day < 10) ? ('0' + day) : (String(day))
let hour = parseInt(count / 60 / 60 % 24)
hour = (hour < 10) ? ('0' + hour) : (String(hour))
let minute = parseInt(count / 60 % 60)
minute = (minute < 10) ? ('0' + minute) : (String(minute))
let secend = parseInt(count % 60)
secend = (secend < 10) ? ('0' + secend) : (String(secend))
// 返回倒计时结果
const result = [day, hour, minute, secend]
return result
}
function main() {
// 输入倒计时的截至日期:
const deadline = '2024-1-14 11:30:00'
// 更新倒计时的截止日期
const span_dl = document.querySelector('#dl')
span_dl.innerHTML = deadline
// 判断合法性
const result = getCountdown(+new Date(deadline))
if (!result) return 1
// 定位各标签对象
const span_d = document.querySelector('#d')
const span_h = document.querySelector('#h')
const span_m = document.querySelector('#m')
const span_s = document.querySelector('#s')
// 更新标签的时间
span_d.innerHTML = result[0]
span_h.innerHTML = result[1]
span_m.innerHTML = result[2]
span_s.innerHTML = result[3]
}
// 网页加载时,先执行一次main函数,达到加载最新数据的效果
main()
// 设置定时器: 此后将1秒自动执行一次main函数,从而达到更新数据的效果
setInterval(main, 1000)
</script>
</body>
倒计时函数(速查)
// 函数说明:
// 参数=截止日期的时间戳
// 返回值=false或者带有倒计时信息的数组
function getCountdown(deadline = +new Date() + (86400 * 1000)) {
const current = +new Date()
const dl = deadline
const count = (dl - current) / 1000 // 1ms 转为 1s 需要除以 1000
if (count < 0) return false
let day = parseInt(count / 60 / 60 / 24)
day = (day < 10) ? ('0' + day) : (String(day))
let hour = parseInt(count / 60 / 60 % 24)
hour = (hour < 10) ? ('0' + hour) : (String(hour))
let minute = parseInt(count / 60 % 60)
minute = (minute < 10) ? ('0' + minute) : (String(minute))
let secend = parseInt(count % 60)
secend = (secend < 10) ? ('0' + secend) : (String(secend))
const result = [day, hour, minute, secend]
return result
}
节点操作
查找节点
- 查找父节点
<body>
<div class="grandfather">
<div class="father">
<div class="son"></div>
</div>
</div>
<script>
const son = document.querySelector('.son')
console.log(son);
console.log(son.parentNode); // parentNode:父节点
console.log(son.parentNode.parentNode);
</script>
</body>
- 查找子节点
<script>
const grandfather = document.querySelector('.grandfather')
console.log(grandfather);
console.log(grandfather.childNodes); // parentNode:父节点
console.log(grandfather.childNodes.childNodes);
</script>
- 查找兄弟节点
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
const li_2 = document.querySelector('ul li:nth-child(2)')
// 上一个兄弟节点
const li_1 = li_2.previousElementSibling
console.log(li_1)
// 下一个兄弟节点
const li_3 = li_2.nextElementSibling
console.log(li_3)
</script>
</body>
增加节点
- 添加到父元素中的最后一个子元素
<body>
<ul></ul>
<script>
const ul = document.querySelector('ul')
// 1. 创建节点
const li = document.createElement('li')
li.innerHTML = '我是新加入的节点'
// 2. 添加到父元素中的最后一个子元素
ul.appendChild(li)
</script>
</body>
- 添加到父元素中的某个子元素的前面
<body>
<ul>
<li>001</li>
<li>002</li>
<li>003</li>
</ul>
<script>
const ul = document.querySelector('ul')
// 1. 创建节点
const li = document.createElement('li')
li.innerHTML = '我是新加入的节点'
// 2. 添加到父元素中的某个子元素的前面
ul.insertBefore(li, ul.children[0])
</script>
</body>
克隆节点
语法:
元素.cloneNode(布尔值)
介绍:
cloneNode 会克隆出一个跟原标签一样的元素,括号内传入布尔值
若为 true,则代表克隆时会包含后代节点一起克隆
若为 false,则代表克隆时不包含后代节点
默认为 false
<body>
<ul>
<li>001</li>
<li>002</li>
<li>003</li>
</ul>
<script>
const ul = document.querySelector('ul')
// 克隆节点
const li_1 = ul.children[0].cloneNode(true)
// 添加节点
ul.appendChild(li_1)
</script>
</body>
删除节点
<body>
<ul>
<li>要删除的内容</li>
<li>Hello</li>
<li>World</li>
</ul>
<script>
const ul = document.querySelector('ul')
// 删除节点(通过父级删除子级元素)
ul.removeChild(ul.children[0])
</script>
</body>
移动端事件
触屏事件(touch) | 说明 |
---|---|
touchstart | 手指触摸到一个 DOM 元素时触发 |
touchmove | 手指在一个 DOM 元素上滑动时触发 |
touchend | 手指从一个 DOM 元素上移动时触发 |
<body>
<div style="width: 200px; height: 200px; background-color: pink;"></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 插件
什么是插件
插件就是别人写好的一些代码,我们只需要复制对应的代码,就可以直接实现对应效果
学习插件的过程
本文以swiper插件为例:
-
熟悉官网,了解这个插件可以完成什么需求 https://www.swiper.com.cn/
-
查看在线演示 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同时使用的时候,类名需要注意区分
Window 对象
浏览器对象模型
- BOM(Browser Object Model)是浏览器对象模型
- window 对象是一个全局对象,也可以说是 JavaScript 中的顶级对象
- 像 document、alert()、console.log() 这些都是属于 window 的
- 所有通过 var 定义在全局作用域中的变量、函数都会变成 window 对象的属性和方法
- window 对象下的属性和方法,在调用时可以省略window,例如
window.document.querySelector()
可以省略为document.querySelector()
location 对象
基本介绍
location 的数据类型是对象,它拆分并保存了 URL 地址的各个组成部分
属性与方法
- href 属性:获取完整的 URL 地址,对其进行赋值操作即可实现"网页的跳转"
<body>
<a href="https://www.baidu.com">
支付成功!<span>5</span>秒钟之后将自动跳转到首页
</a>
<script>
// 实现网页的自动跳转
// 1.获取元素对象
const a = document.querySelector('a')
// 2.实现倒计时
let time = 5
let n = setInterval(function () {
a.innerHTML = `支付成功!<span>${--time}</span>秒钟之后将自动跳转到首页`
if (time === 0) {
clearInterval(n)
// 实现网页跳转
location.href = "https://www.baidu.com"
}
}, 1000)
</script>
</body>
- search 属性
说明:
search 属性获取地址中携带的参数(即:符号" ? "后面的部分)
例如:
console.log(location.search)
- hash 属性
说明:
hash 属性获取地址中的哈希值(即:符号" # "后面的部分)
例如:
console.log(location.hash)
- reload 方法
reload 方法用来刷新当前页面,传入参数 true 时表示强制刷新
<body>
<button style="margin: 0 auto; width: 200px; height: 200px; background-color: pink;">刷新页面</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click', function () {
// 相当于 F5
location.reload(true) // true:启用强制刷新
})
</script>
</body>
navigation 对象
基本介绍
navigation 的数据类型是对象,该对象下记录了浏览器自身的相关信息
属性与方法
- userAgent:通过它检测浏览器的版本及平台
<script>
// 检测userAgent(浏览器信息)
(function () {
const userAgent = navigator.userAgent
// 验证是否为 Android 或 iPhone
const android = userAgent.match(/(Android);?[\s\/]+([\d.]+)?/)
const iphone = userAgent.match(/(iPhone\sOS)\s([\d_]+)/)
// 如果是 Android 或 iPhone,则跳转到移动站点
if (android || iphone) {
location.href = 'https://手机端页面.cn/'
}
})()
</script>
history 对象
基本介绍
history 的数据类型是对象,主要管理历史记录,该对象与浏览器地址栏的操作相对应,如前进、后退、历史记录等
属性与方法
history对象方法 | 作用 |
---|---|
back() | 后退功能 |
forward() | 前进功能 |
go() | 参数为1前进1个页面,参数为-1则后退1个页面 |
<body>
<button>回退</button>
<button>前进</button>
<script>
const back = document.querySelector('button')
const forword = back.nextElementSibling
back.addEventListener('click', function () {
// 后退一步
// history.back()
history.go(-1)
})
forword.addEventListener('click', function () {
// 前进一步
// history.forword()
history.go(1)
})
</script>
</body>
本地存储
具体介绍
背景:
随着互联网的快速发展,基于网页的应用越来越普遍,同时也变得越来越复杂。
为了满足各种各样的需求,会经常性在本地存储大量的数据。
HTML5规范提出了相关解决方案。
其他:
1.数据存储在用户浏览器中
2.设置、读取方便,甚至页面刷新不丢失数据
3.容量较大,sessionStorage 和 localStorage 约为 5M 左右
4.常见的使用场景:https://todomvc.com/examples/vanilla-es6/(页面刷新数据不丢失)
分类
- localStorage
作用:
可以将数据永久存储在本地(用户的电脑),除非手动删除,否则关闭页面也会存在
特性:
可以多个窗口(页面)共享(同一浏览器可以共享)
以键值对的形式存储使用
<script>
// 存储数据
localStorage.setItem('name', 'Jack')
// 修改数据
localStorage.setItem('name', 'Peter')
// 读取数据
console.log(localStorage.getItem('name'));
// 删除数据
localStorage.removeItem('name')
</script>
- sessionStorage
特性:
生命周期为关闭浏览器窗口
在同一个窗口(页面)下数据可以共享
以键值对的形式存储使用
用法跟 localStorage 基本相同
<script>
// 存储数据
sessionStorage.setItem('name', 'Jack')
// 修改数据
sessionStorage.setItem('name', 'Peter')
// 读取数据
console.log(sessionStorage.getItem('name'));
// 删除数据
sessionStorage.removeItem('name')
</script>
存储复杂数据类型
基本介绍
问题:
本地存储只能存储字符串,无法存储复杂数据类型
解决:
需要将复杂数据类型转换成 JSON 字符串,存储到本地
语法:
JSON.stringify(复杂数据类型)
具体演示
<script>
const object = {
name: 'Jack',
age: 30,
gender: '男'
}
// 存储对象:
// 1.复杂数据类型转为JSON字符串
const str1 = JSON.stringify(object)
// 2.存储JSON字符串
localStorage.setItem('obj', str1)
// 读取对象:
// 1.读取JSON字符串
const str2 = localStorage.getItem('obj')
// 2.将JSON字符串转为"对象"
const obj = JSON.parse(str2)
console.log(obj);
</script>