文章目录
BOM简介
- BOM(Browser Object Model ) 是浏览器对象模型
- window 是浏览器内置中的全局对象,我们所学习的所有
Web APIs
的知识内容都是基于window
对象实现的. - window 对象下包含了
navigator
、location
、document
、history
、screen
5个属性,即所谓的 BOM (浏览器对象模型) - document 是实现 DOM 的基础,它其实是依附于 window 的属性。
- 注:依附于 window 对象的所有属性和方法,使用时可以省略 window
如下代码在日常使用时都省略了window。
// window.setInterval()
addEventListener('scroll', function () {
console.log(111)
})
window.alert()
window.prompt()
console.log(window) //输出window对象
定时器-延时函数
JavaScript
内置的一个用来让代码延迟执行的函数,叫setTimeout
- 语法:
setTimeout(回调函数,等待的毫秒数)
setTimeout
仅仅只执行一次,所以可以理解为就是把一段代码延迟执行, 平时省略window
- 清除延时函数:
let timer=setTimeout(回调函数,等待的毫秒数)
clearTimeout(timer)
5秒关闭广告案例
<img src="./images/ad.png" alt="">
<script>
let img = document.querySelector('img')
setTimeout(function () {
img.style.display = 'none'
}, 3000)
</script>
递归模拟setInterval函数
// 利用递归函数 模拟了 setinterval
let div = document.querySelector('div')
function fn() {
div.innerHTML = new Date().toLocaleString()
setTimeout(fn, 1000) //fn里调用fn
}
fn()
两种定时器对比
setInterval
的特征是重复执行,首次执行会延时setTimeout
的特征是延时执行,只执行 1 次setTimeout
结合递归函数,能模拟setInterval
重复执行clearTimeout
清除由setTimeout
创建的定时任务
JS 执行机制
结果都是
javaScript 语言的一大特点就是单线程,
比如我们对某个 DOM 元素进行添加和删除操作,不能同时进行。 应该先进行添加,之后再删除。
JS 单线程导致的问题是: 如果 JS 执行的时间过长,这样就会造成页面的渲染不连贯,导致页面渲染加载阻塞的感觉。
为了解决这个问题,利用多核 CPU 的计算能力,HTML5 提出 Web Worker 标准,允许JavaScript 脚本创建多个线程。于是,JS 中出现了同步和异步。
由于主线程不断的重复获得任务、执行任务、再获取任务、再执行,所以这种机制被称为事件循环(event loop)
location对象
location
的数据类型是对象
,它拆分并保存了 URL 地址的各个组成部分
常用属性和方法:
href
属性获取完整的 URL 地址,对其赋值时用于地址的跳转
//可以得到当前文件的URL地址
console.log(location.href)
//可以通过JS方式跳转到目标地址
location.href='http://www.baidu.com'
5秒之后跳转页面部分代码:
<a href="http://www.itcast.cn">支付成功,<span>5</span> 秒之后跳转首页</a>
<script>
let a = document.querySelector('a')
let num = 5
let timer = setInterval(function () {
num--
a.innerHTML = `支付成功,<span>${num}</span> 秒之后跳转首页`
if (num === 0) {
clearInterval(timer)
// 跳转页面
location.href = 'http://www.itcast.cn'
}
}, 1000)
</script>
search
属性获取地址中携带的参数,符号 ?后面部分
location.search.html
文件写个表单
<form action="target.html">
<input type="text" name="username" value="submit content">
<button>提交</button>
</form>
target.html
用于接受表单内容
<div>我就是target</div>
<script>
console.log(location.search)
</script>
在location.search.html
提交之后,target.html
控制台的输出如下
target.html
本地链接:
file:///C:/xxxxx/xxxxx/xxxxxx/xxxx/xxxx/target.html ?username=submit+content
hash
属性获取地址中的啥希值,符号 # 后面部分
<a href="#one">第一个</a>
<a href="#two">第二个</a>
<script>
console.log(location.hash) //点击任意a,刷新,控制台输出#one或者#two
</script>
后期vue路由的铺垫,经常用于不刷新页面,显示不同页面,比如 网易云音乐
reload
方法用来刷新当前页面,传入参数 true 时表示强制刷新
<button>刷新</button>
<script>
let btn = document.querySelector('button')
btn.addEventListener('click', function () {
// reload() 刷新方法 有本地缓存 强制刷新 ctrl + f5 直接更新最新内容从网上拉去,不走本地缓存
location.reload(true)
})
</script>
navigator对象
navigator
的数据类型是对象,该对象下记录了浏览器自身的相关信息
常用属性和方法:
通过userAgent
检测浏览器的版本及平台
// 检测 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 = 'http://m.itcast.cn'
}
})()
histroy对象(了解)
swiper插件
学习插件的基本过程
- 熟悉官网,了解这个插件可以完成什么需求 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同时使用的时候, 类名需要注意区分
用swiper插件可以很快的做出一个轮播图效果!(cv工程师)
localStorage本地存储
存储数据:
localStorage.setItem(key, value)
获取数据:
localStorage.getItem(key)
删除数据:
localStorage.removeItem(key)
本地只能存储字符串,无法存储复杂数据类型(如object类型).需要将复杂数据类型转换成JSON
字符串,再存储到本地。
- 将复杂数据转换成
JSON
字符串存储本地存储中
JSON.stringify(复杂数据类型)
- 将
JSON
字符串转换成对象取出时候使用
JSON.parse(JSON字符串)
实际案例部分代码:
let obj = {
uname: '荻畔拂风',
age: 17,
address: '港珠澳大桥桥洞下'
}
// 将复杂数据转换成JSON字符串 存储 本地存储中
localStorage.setItem("obj", JSON.stringify(obj))
let id = localStorage.getItem('obj') //此时id是字符串类型
console.log(typeof id) //string
// 将JSON字符串转换成对象 取出 时候使用
console.log(typeof JSON.parse(id)) //此时id是object类型
console.log(JSON.parse(id))
// 删除数据
// localStorage.removeItem('obj')
json格式的键和值最好都是双引号
sessionStorage(了解)
1、生命周期为关闭浏览器窗口
2、在同一个窗口(页面)下数据可以共享
3. 以键值对的形式存储使用
4. 用法跟localStorage 基本相同
购物车案例(自我升级版)
视频教程没有实现复选框功能和商品与总价之间的关联,但是在常用的一些商品软件是应该做到这样的功能。今晚搞了挺久,想起来是结合前面全选和反选的案例加上就能完成的功能,也实现了。
核心思想:
首先对复选框和全选框都加上监听;(基本就是之前全选反选案例的代码)
总价和个数的计算函数中,记得加个判断
//总价和个数
function result() {
let sum = 0
let num = 0
let checks = document.querySelectorAll('.s_ck') //这里加上是因为如果商品被删除,要重新计复选框的数量
for (let i = 0; i < checks.length; i++) {
console.log(checks[i].checked)
if (checks[i].checked) { //判断是否为true(是否被选中)
sum = sum + parseInt(totals[i].innerText)
num = num + parseInt(inputs[i].value)
}
}
// console.log(sum)
totalPrice.innerText = sum + '¥'
// console.log(num)
totalCount.innerText = num
}
本地存储学习信息案例
html:
<!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>Document</title>
<link rel="stylesheet" href="css/user.css">
</head>
<body>
<h1>新增学员</h1>
<div class="info">
姓名:<input type="text" class="uname">
年龄:<input type="text" class="age">
性别: <select name="gender" id="" class="gender">
<option value="男">男</option>
<option value="女">女</option>
</select>
薪资:<input type="text" class="salary">
就业城市:<select name="city" id="" class="city">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
<option value="曹县">曹县</option>
</select>
<button class="add">录入</button>
</div>
<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>
// 读取本地存储的数据 封装为函数
// 需求①:读取本地存储数据(封装函数)
// 如果本地存储有数据,则返回 JSON.parse() 之后的对象
// 如果本地存储没有数据,则默认写入三条数据,注意存储的利用JSON.stringify() 存 储JSON 格式的数据
function getLocalData() {
let data = localStorage.getItem('data')
if (data) {
// 如果本地存储有数据,则返回 JSON.parse() 之后的对象
return JSON.parse(data) // {xxxxx}
} else {
// 如果本地存储没有数据,则默认写入三条数据,注意存储的利用JSON.stringify() 存 储JSON 格式的数据
let arr = [
{ stuId: 1001, uname: '欧阳霸天', age: 19, gender: '男', salary: '20000', city: '上海' },
{ stuId: 1002, uname: '令狐霸天', age: 29, gender: '男', salary: '30000', city: '北京' },
{ stuId: 1003, uname: '诸葛霸天', age: 39, gender: '男', salary: '2000', city: '北京' },
]
// 写入到本地存储里面
localStorage.setItem('data', JSON.stringify(arr))
}
}
// 先调用一次
getLocalData()
// 获取父元素 tbody
let tbody = document.querySelector('tbody')
// 添加数据按钮
// 获取录入按钮
let add = document.querySelector('.add')
// 获取各个表单的元素
let uname = document.querySelector('.uname')
let age = document.querySelector('.age')
let gender = document.querySelector('.gender')
let salary = document.querySelector('.salary')
let city = document.querySelector('.city')
// 渲染函数 把数组里面的数据渲染到页面中
function render() {
// 需求②:渲染模块
// 先读取本地存储数据,然后渲染
let arr = getLocalData()
// 先干掉以前的数据 让tbody 里面原来的tr 都没有
tbody.innerHTML = ''
// 在渲染新的数据
// 根据数据的条数来渲染增加 tr
for (let i = 0; i < arr.length; i++) {
// 1.创建tr
let tr = document.createElement('tr')
// 2.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>
`
// 3.把tr追加给 tobdy 父元素.appendChild(子元素)
tbody.appendChild(tr)
}
}
// 页面加载就调用函数
render()
add.addEventListener('click', function () {
// 需求③:添加模块
// 注意,先取的最新的本地存储数据,然后追加
let arr = getLocalData()
// 新增了数据,要把新数据存储到本地存储别,忘记转换
// 获得表单里面的值 之后追加给 数组 arr 用 push方法
arr.push({
// 得到数组最后一条数据的学号 1003 + 1
stuId: arr[arr.length - 1].stuId + 1,
uname: uname.value,
age: age.value,
gender: gender.value,
salary: salary.value,
city: city.value
})
// console.log(arr)
// 存储到仓库里面
localStorage.setItem('data', JSON.stringify(arr))
// 重新渲染我们的函数
render()
// 复原所有的表单数据
uname.value = age.value = salary.value = ''
gender.value = '男'
city.value = '北京'
})
// 删除操作, 删除的也是数组里面的数据 , 但是我们用事件委托
tbody.addEventListener('click', function (e) {
// 读取本地存储里面的数据
let arr = getLocalData()
// 怎么知道点击了a?
// console.dir(e.target.tagName)
if (e.target.tagName === 'A') {
// 删除 数组里面的数据 arr.splice(从哪里开始删,1)
// 得到a的id
// console.log(e.target.dataset.id)
arr.splice(e.target.dataset.id, 1)
// 存到本地里面
localStorage.setItem('data', JSON.stringify(arr))
// 重新渲染我们的函数
render()
}
})
</script>
</body>
</html>
user.css:
* {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
color:#721c24;
}
h1 {
text-align: center;
color:#333;
margin: 20px 0;
}
table {
margin:0 auto;
width: 800px;
border-collapse: collapse;
color:#004085;
}
th {
padding: 10px;
background: #cfe5ff;
font-size: 20px;
font-weight: 400;
}
td,th {
border:1px solid #b8daff;
}
td {
padding:10px;
color:#666;
text-align: center;
font-size: 16px;
}
tbody tr {
background: #fff;
}
tbody tr:hover {
background: #e1ecf8;
}
.info {
width: 900px;
margin: 50px auto;
text-align: center;
}
.info input {
width: 80px;
height: 25px;
outline: none;
border-radius: 5px;
border:1px solid #b8daff;
padding-left: 5px;
}
.info button {
width: 60px;
height: 25px;
background-color: #004085;
outline: none;
border: 0;
color: #fff;
cursor: pointer;
border-radius: 5px;
}
.info .age {
width: 50px;
}