第一天
let和const用法区别
DOM文档对象模型,操作网页内容,可以开发网页内容特效和实现用户交互
dom对象
<body>
<div>123</div>
<script>
const div = document.querySelector('div')
console.dir(div)
</script>
</body>
获取dom元素
获取dom对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<!-- <div>123</div>
<script>
const div = document.querySelector('div')
console.dir(div)
</script> -->
<div class="box">123</div>
<div class="box">abc</div>
<p id="nav">导航栏</p>
<ul>
<li>测试1</li>
<li>测试2</li>
<li>测试3</li>
</ul>
<script>
//获取匹配的第一个元素
/* const box = document.querySelector('div')
const box = document.querySelector('.box')
console.log(box) */
/* const nav = document.querySelector('#nav')
console.log(nav) */
/* const li = document.querySelector('ul li:first-child')
console.log(li) */
const lis = document.querySelectorAll('ul li')
console.log(lis)
</script>
</body>
</html>
修改对象内容
innerText不解析标签
<div class="box">hhhhhh</div>
<script>
const box = document.querySelector('.box')
//修改文字内容 对象.innerText 属性
console.log(box.innerText) //获取文字内容
box.innerText='啊啊啊啊'
</script>
innerHTML解析标签
<div class="box">hhhhhh</div>
<script>
const box = document.querySelector('.box')
//修改文字内容 对象.innerText 属性
/* console.log(box.innerText) //获取文字内容
box.innerText='啊啊啊啊' */
console.log(box.innerHTML)
// box.innerHTML='aaaa'
box.innerHTML='<strong>dddd</strong>'
</script>
抽奖案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.wrapper{
width:840px;
height: 420px;
background: url(./images/1.jpg) no-repeat center / cover;
padding: 100px 250px;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="wrapper">
<strong>抽奖</strong>
<h1>一等奖:<span id="one"></span></h1>
<h2>二等奖:<span id="two"></span></h2>
<h3>三等奖:<span id="three"></span></h3>
</div>
<script>
//声明数组
const personArr = ['小红','小明','小军','小丽']
//随机数 数组的下标
//一等奖
const random = Math.floor(Math.random() *personArr.length)
//获取one元素
const one = document.querySelector('#one')
//把名字给one
one.innerHTML = personArr[random]
//删除这个名字
personArr.splice(random,1)
// console.log(personArr)
//二等奖
const random2 = Math.floor(Math.random() *personArr.length)
//获取one元素
const two = document.querySelector('#two')
//把名字给one
two.innerHTML = personArr[random2]
//删除这个名字
personArr.splice(random2,1)
// console.log(personArr)
//二等奖
const random3 = Math.floor(Math.random() *personArr.length)
//获取one元素
const three = document.querySelector('#three')
//把名字给one
three.innerHTML = personArr[random3]
//删除这个名字
personArr.splice(random3,1)
// console.log(personArr)
</script>
</body>
</html>
修改元素常见属性
<img src="./images/1.jpg" alt="">
<script>
//获取图片元素
const img = document.querySelector('img')
//修改图片对象的属性 对象.属性=值
img.src='./images/2.jpg'
img.title='好想出去玩'
</script>
随机显示图片案例
<img src="./images/1.jpg" alt="">
<script>
function getRandom(N,M){
return Math.floor(Math.random() *(M-N+1))+N
}
//获取图片对象
const img = document.querySelector('img')
//随机得到序号
const random=getRandom(1,10)
//更换路径
img.src=`./images/${random}.jpg`
</script>
通过style属性修改样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
//获取元素
const box =document.querySelector('.box')
//修改样式属性 对象.style.样式属性='值' 要跟单位
box.style.width = '300px'
//多组单词的采取 小驼峰命名法
box.style.backgroundColor='skyblue'
//加上边框
box.style.borderTop='2px solid red'
</script>
</body>
</html>
随机更换背景图片案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background:url(./images/1.jpg) no-repeat top center / cover;
}
</style>
</head>
<body>
<script>
function getRandom(N,M){
return Math.floor(Math.random()*(M-N+1))+N
}
const random = getRandom(1,10)
document.body.style.backgroundImage=`url(./images/${random}.jpg)`
</script>
</body>
</html>
操作样式属性
随机轮播图案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
box-sizing: border-box;
}
.slider{
width: 560px;
height: 400px;
overflow: hidden;
}
.slider-wrapper{
width:100%;
height: 320px;
}
.slider-wrapper img{
width: 100%;
height: 100%;
display: block;
}
.slider-footer{
height: 80px;
background-color: rgb(100, 67, 68);
padding: 12px 12px 0 12px;
position: relative;
}
.slider-footer .toggle{
position: absolute;
right: 0;
top:12px;
display: flex;
}
.slider-footer .toggle button{
margin-right: 12px;
width: 28px;
height: 28px;
appearance: none;
border: none;
background: rgba(255,255,255,0.1);
color: #fff;
border-radius: 4px;
cursor: pointer;
}
.slider-footer .toggle button:hover{
background: rgba(255,255,255,0.2);
}
.slider-footer p{
margin: 0;
color: #fff;
font-size: 18px;
margin-bottom: 10px;
}
.slider-indicator{
margin: 0;
padding: 0;
list-style: none;
display: flex;
align-items: center;
}
.slider-indicator li{
width: 8px;
height: 8px;
margin: 4px;
border-radius: 50%;
background: #fff;
opacity: 0.4;
cursor: pointer;
}
.slider-indicator li.active{
width: 12px;
height: 12px;
opacity: 1;
}
</style>
</head>
<body>
<div class="slider">
<div class="slider-wrapper">
<img src="./images/1.jpg" alt=""/>
</div>
<div class="slider-footer">
<p>aaaaaaaa</p>
<ul class="slider-indicator">
<li ></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="toggle">
<button class="prev"><</button>
<button class="next">></button>
</div>
</div>
</div>
<script>
//初始化数据
const sliderData=[
{url:'./images/1.jpg',title:'aaaaaa',color:'rgb(100,67,68)'},
{url:'./images/2.jpg',title:'bbbbbb',color:'rgb(43,35,26)'},
{url:'./images/3.jpg',title:'cccccc',color:'rgb(36,31,33)'},
{url:'./images/4.jpg',title:'dddddd',color:'rgb(139,98,66)'},
{url:'./images/5.jpg',title:'eeeeee',color:'rgb(67,90,92)'},
]
//需要随机数
const random = parseInt(Math.random() *sliderData.length)
//获取图片
const img = document.querySelector('.slider-wrapper img')
//修改图片路径=对象.url
img.src=sliderData[random].url
//获取p
const p = document.querySelector('.slider-footer p')
//修改p
p.innerHTML=sliderData[random].title
//修改背景颜色
const footer = document.querySelector('.slider-footer')
footer.style.backgroundColor = sliderData[random].color
//小圆点
const li = document.querySelector(`.slider-indicator li:nth-child(${random+1})`)
//让当前这个小li 添加active这个类
li.classList.add('active')
</script>
</body>
</html>
操作表单元素属性
<body>
<!-- <input type="text" value="电脑"> -->
<input type="checkbox" name="" id="">
<button>点击</button>
<script>
const uname = document.querySelector('input')
// uname.type='password'
//获取
const ipt = document.querySelector('input')
ipt.checked=true
//获取
const button = document.querySelector('button')
button.disabled = true//禁用
</script>
</body>
自定义属性
<body>
<div data-id="1" data-spm="hh">1</div>
<div data-id="2">2</div>
<div data-id="3">3</div>
<div data-id="4">4</div>
<div data-id="5">5</div>
<script>
const one = document.querySelector('div')
console.log(one.dataset.id)
console.log(one.dataset.spm)
</script>
</body>
定时器(间歇函数)
<script>
setInterval(function(){
console.log('一秒执行一次')
},1000)
</script>
<script>
function fn(){
console.log('一秒执行一次')
}
setInterval(fn,1000)
</script>
<script>
function fn(){
console.log('一秒执行一次')
}
let n = setInterval(fn,1000)
console.log(n)
//关闭定时器
clearInterval(n)
</script>
阅读注册协议案例
<!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>
<textarea name="" id="" cols="30" rows="10">
用户注册协议
欢迎使用xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
</textarea>
<br>
<button class="btn" disabled>我已阅读用户协议(60)</button>
<script>
const btn = document.querySelector('.btn')
// console.log(btn.innerHTML)
//倒计时
let i = 60
let n = setInterval(function(){
i--
btn.innerHTML = `我已阅读用户协议(${i})`
if(i===0){
clearInterval(n)
//定时器停了就开按钮
btn.disabled=false
btn.innerHTML='同意'
}
},1000)
</script>
</body>
</html>
轮播图定时器案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
box-sizing: border-box;
}
.slider{
width: 560px;
height: 400px;
overflow: hidden;
}
.slider-wrapper{
width:100%;
height: 320px;
}
.slider-wrapper img{
width: 100%;
height: 100%;
display: block;
}
.slider-footer{
height: 80px;
background-color: rgb(100, 67, 68);
padding: 12px 12px 0 12px;
position: relative;
}
.slider-footer .toggle{
position: absolute;
right: 0;
top:12px;
display: flex;
}
.slider-footer .toggle button{
margin-right: 12px;
width: 28px;
height: 28px;
appearance: none;
border: none;
background: rgba(255,255,255,0.1);
color: #fff;
border-radius: 4px;
cursor: pointer;
}
.slider-footer .toggle button:hover{
background: rgba(255,255,255,0.2);
}
.slider-footer p{
margin: 0;
color: #fff;
font-size: 18px;
margin-bottom: 10px;
}
.slider-indicator{
margin: 0;
padding: 0;
list-style: none;
display: flex;
align-items: center;
}
.slider-indicator li{
width: 8px;
height: 8px;
margin: 4px;
border-radius: 50%;
background: #fff;
opacity: 0.4;
cursor: pointer;
}
.slider-indicator li.active{
width: 12px;
height: 12px;
opacity: 1;
}
</style>
</head>
<body>
<div class="slider">
<div class="slider-wrapper">
<img src="./images/1.jpg" alt=""/>
</div>
<div class="slider-footer">
<p>aaaaaaaa</p>
<ul class="slider-indicator">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="toggle">
<button class="prev"><</button>
<button class="next">></button>
</div>
</div>
</div>
<script>
//初始化数据
const sliderData=[
{url:'./images/1.jpg',title:'aaaaaa',color:'rgb(100,67,68)'},
{url:'./images/2.jpg',title:'bbbbbb',color:'rgb(43,35,26)'},
{url:'./images/3.jpg',title:'cccccc',color:'rgb(36,31,33)'},
{url:'./images/4.jpg',title:'dddddd',color:'rgb(139,98,66)'},
{url:'./images/5.jpg',title:'eeeeee',color:'rgb(67,90,92)'},
]
//获取元素
const img = document.querySelector('.slider-wrapper img')
const p = document.querySelector('.slider-footer p')
let i = 0
//开启定时器
setInterval(function(){
i++
//衔接位置
if(i>=sliderData.length){
i=0
}
//更换图片路径
img.src = sliderData[i].url
//把字写到p里面
p.innerHTML = sliderData[i].title
//小圆点
//先删除之前的active
document.querySelector('.slider-indicator .active').classList.remove('active')
//只让当前的添加active
document.querySelector(`.slider-indicator li:nth-child(${i+1})`).classList.add('active')
},1000)
</script>
</body>
</html>
第二天
事件监听
语法:元素对象.addEventListener(‘事件类型’,要执行的函数)
关闭广告案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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>
<div class="box1">X</div>
<script>
const box1 = document.querySelector('.box1')
const box = document.querySelector('.box')
box1.addEventListener('click',function(){
box.style.display='none'
})
</script>
</body>
</html>
随机点名案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
h2{
text-align: center;
}
.box{
width:600px;
margin: 50px auto;
display: flex;
font-size: 25px;
line-height: 40px;
}
.qs{
width: 450px;
height: 40px;
color: red;
}
.btns {
text-align: center;
}
.btns button{
width: 120px;
height: 35px;
margin: 0 50px;
}
</style>
</head>
<body>
<h2>随机点名</h2>
<div class="box">
<span>名字是:</span>
<div class="qs">这里显示姓名</div>
</div>
<div class="btns">
<button class="start">开始</button>
<button class="end">结束</button>
</div>
<script>
const arr = ['小a','小b','小c','小d','小e','小f']
//定时器的全局变量
let timerId = 0
//随机号要全局变量
let random = 0
//开始按钮模块
const qs = document.querySelector('.qs')
//获取开始按钮对象
const start = document.querySelector('.start')
//添加点击事件
start.addEventListener('click',function(){
timerId = setInterval(function(){
random = parseInt(Math.random() *arr.length)
qs.innerHTML = arr[random]
},35)
//只有一个了,不需要抽取了 让两个按钮禁用
if(arr.length === 1){
start.disabled = true
end.disabled = true
}
})
//关闭按钮模块
const end =document.querySelector('.end')
end.addEventListener('click',function(){
clearInterval(timerId)
//结束了删除抽到的元素
arr.splice(random,1)
console.log(arr)
})
</script>
</body>
</html>
事件类型
轮播图完整版案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
box-sizing: border-box;
}
.slider{
width: 560px;
height: 400px;
overflow: hidden;
}
.slider-wrapper{
width:100%;
height: 320px;
}
.slider-wrapper img{
width: 100%;
height: 100%;
display: block;
}
.slider-footer{
height: 80px;
background-color: rgb(100, 67, 68);
padding: 12px 12px 0 12px;
position: relative;
}
.slider-footer .toggle{
position: absolute;
right: 0;
top:12px;
display: flex;
}
.slider-footer .toggle button{
margin-right: 12px;
width: 28px;
height: 28px;
appearance: none;
border: none;
background: rgba(255,255,255,0.1);
color: #fff;
border-radius: 4px;
cursor: pointer;
}
.slider-footer .toggle button:hover{
background: rgba(255,255,255,0.2);
}
.slider-footer p{
margin: 0;
color: #fff;
font-size: 18px;
margin-bottom: 10px;
}
.slider-indicator{
margin: 0;
padding: 0;
list-style: none;
display: flex;
align-items: center;
}
.slider-indicator li{
width: 8px;
height: 8px;
margin: 4px;
border-radius: 50%;
background: #fff;
opacity: 0.4;
cursor: pointer;
}
.slider-indicator li.active{
width: 12px;
height: 12px;
opacity: 1;
}
</style>
</head>
<body>
<div class="slider">
<div class="slider-wrapper">
<img src="./images/1.jpg" alt=""/>
</div>
<div class="slider-footer">
<p>aaaaaaaa</p>
<ul class="slider-indicator">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="toggle">
<button class="prev"><</button>
<button class="next">></button>
</div>
</div>
</div>
<script>
//初始化数据
const data=[
{url:'./images/1.jpg',title:'aaaaaa',color:'rgb(100,67,68)'},
{url:'./images/2.jpg',title:'bbbbbb',color:'rgb(43,35,26)'},
{url:'./images/3.jpg',title:'cccccc',color:'rgb(36,31,33)'},
{url:'./images/4.jpg',title:'dddddd',color:'rgb(139,98,66)'},
{url:'./images/5.jpg',title:'eeeeee',color:'rgb(67,90,92)'},
]
//获取元素
const img = document.querySelector('.slider-wrapper img')
const p = document.querySelector('.slider-footer p')
const footer = document.querySelector('.slider-footer ')
//右按钮
const next = document.querySelector('.next')
//信号量 控制播放图片张数
let i = 0
//注册点击事件
next.addEventListener('click',function(){
i++
//如果大于长度复原为0
/* if(i>=data.length){
i=0
} */
i=i>=data.length?0:i
toggle()
//渲染对应的数据
// console.log(data[i])
/* img.src = data[i].url
p.innerHTML = data[i].title
footer.style.backgroundColor = data[i].color
//小圆点
document.querySelector('.slider-indicator .active').classList.remove('active')
document.querySelector(`.slider-indicator li:nth-child(${i+1})`).classList.add('active')
*/ })
//左按钮
const prev = document.querySelector('.prev')
//注册点击事件
prev.addEventListener('click',function(){
i--
//如果小于0 跳到最后一张
/* if(i<0){
i=data.length-1
} */
i=i<0?data.length-1:i
toggle()
})
//渲染对应的数据
// console.log(data[i])
function toggle(){
img.src = data[i].url
p.innerHTML = data[i].title
footer.style.backgroundColor = data[i].color
//小圆点
document.querySelector('.slider-indicator .active').classList.remove('active')
document.querySelector(`.slider-indicator li:nth-child(${i+1})`).classList.add('active')
}
//自动播放
let timerId = setInterval(function(){
//利用js自动调用点击事件 click()
next.click()
},1000)
//鼠标经过大盒子停止定时器
const slider = document.querySelector('.slider')
//注册事件
slider.addEventListener('mouseenter',function(){
//停止定时器
clearInterval(timerId)
})
//鼠标离开大盒子开始定时器
//注册事件
slider.addEventListener('mouseleave',function(){
//停止定时器
clearInterval(timerId)
//开启定时器
timerId = setInterval(function(){
//利用js自动调用点击事件 click()
next.click()
},1000)
})
</script>
</body>
</html>
也可以复写调用函数
小米搜索框案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul{
list-style: none;
}
.mi{
position: relative;
width: 223px;
margin: 100px auto;
}
.mi input{
width: 223px;
height: 48px;
padding: 0 10px;
font-size: 14px;
line-height: 48px;
border: 1px solid #e0e0e0;
outline:none;
}
.mi .search{
border: 1px solid #ff6700;
}
.result-list{
display: none;
position: absolute;
left:0;
top:48px;
width:223px;
border: 1px solid #ff6700;
border-top:0;
background: #fff;
}
.result-list a{
display: block;
padding: 6px 15px;
font-size: 12px;
color: #424242;
text-decoration: none;
}
.result-list a:hover{
background-color: #eee;
}
</style>
</head>
<body>
<div class="mi">
<input type="search" placeholder="小米笔记本">
<ul class="result-list">
<li><a href="#">全部商品</a></li>
<li><a href="#">小米11</a></li>
<li><a href="#">小米10s</a></li>
<li><a href="#">小米笔记本</a></li>
<li><a href="#">小米手机</a></li>
<li><a href="#">小米耳机</a></li>
</ul>
</div>
<script>
//获取元素
const input = document.querySelector('[type=search]')
const ul = document.querySelector('.result-list')
//监听事件 获得焦点
input.addEventListener('focus',function(){
//ul显示
ul.style.display = 'block'
//添加一个带有颜色边框的类名
input.classList.add('search')
})
//监听事件 失去焦点
input.addEventListener('blur',function(){
ul.style.display = 'none'
input.classList.remove('search')
})
</script>
</body>
</html>
键盘事件
评论字数统计案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* input{
width: 200px;
transition: all .3s;
}
input:focus{
width: 300px;
} */
.wrapper{
min-width: 400px;
max-width: 800px;
display: flex;
justify-content: flex-end;
}
.avatar{
width: 48px;
height: 48px;
border-radius: 50%;
overflow: hidden;
background: url(./images/2.jpg) no-repeat center / cover;
margin-right: 20px;
}
.wrapper textarea{
outline: none;
border-color: transparent;
resize: none;
background: #f5f5f5;
border-radius: 4px;
flex:1;
padding: 10px;
transition: all 0.5s;
height: 30px;
}
.wrapper textarea:focus{
border-color: #e4e4e4;
background: #fff;
height: 50px;
}
.wrapper button{
background: #00aeec;
color: #fff;
border: none;
border-radius: 4px;
margin-left: 10px;
width: 70px;
cursor: pointer;
}
.wrapper .total{
margin-right: 80px;
color: #999;
margin-top: 5px;
opacity: 0;
transition: all 0.5s;
}
.list{
min-width: 400px;
max-width: 800px;
display: flex;
}
.list .item{
width: 100%;
display: flex;
}
.list .item .info{
flex:1;
border-bottom: 1px dashed #e4e4e4;
padding-bottom: 10px;
}
.list .item p{
margin: 0;
}
.list .item .name{
color: #FB7299;
font-size: 14px;
font-weight: bold;
}
.list .item .text{
color:#333;
padding: 10px 0;
}
.list .item .time{
color: #999;
font-size: 12px;
}
</style>
</head>
<body>
<!-- <input type="text"> -->
<div class="wrapper">
<i class="avater"></i>
<textarea id="tx" placeholder="发一条友善评论" rows="2" maxlength=""></textarea>
<button>发布</button>
</div>
<div class="wrapper">
<span class="total">0/200字</span>
</div>
<div class="list">
<div class="item" style="display: none;">
<i class="avatar"></i>
<div class="info">
<p class="name">清风徐来</p>
<p class="text">大家辛苦了,感谢大家的努力</p>
<p class="time">2024.01.20</p>
</div>
</div>
</div>
<script>
const tx = document.querySelector('#tx')
const total = document.querySelector('.total')
//获得焦点就显示
tx.addEventListener('focus',function(){
total.style.opacity=1
})
//失去焦点就隐藏
tx.addEventListener('blur',function(){
total.style.opacity=0
})
//检测用户输入
tx.addEventListener('input',function(){
total.innerHTML = `${tx.value.length}/200字`
})
</script>
</body>
</html>
获取事件对象
<input type="text">
<script>
const input = document.querySelector('input')
input.addEventListener('keyup',function(e){
if(e.key === 'Enter'){
console.log('按回车')
}
})
</script>
回车发表评论案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* input{
width: 200px;
transition: all .3s;
}
input:focus{
width: 300px;
} */
.wrapper{
min-width: 400px;
max-width: 800px;
display: flex;
justify-content: flex-end;
}
.avatar{
width: 48px;
height: 48px;
border-radius: 50%;
overflow: hidden;
background: url(./images/2.jpg) no-repeat center / cover;
margin-right: 20px;
}
.wrapper textarea{
outline: none;
border-color: transparent;
resize: none;
background: #f5f5f5;
border-radius: 4px;
flex:1;
padding: 10px;
transition: all 0.5s;
height: 30px;
}
.wrapper textarea:focus{
border-color: #e4e4e4;
background: #fff;
height: 50px;
}
.wrapper button{
background: #00aeec;
color: #fff;
border: none;
border-radius: 4px;
margin-left: 10px;
width: 70px;
cursor: pointer;
}
.wrapper .total{
margin-right: 80px;
color: #999;
margin-top: 5px;
opacity: 0;
transition: all 0.5s;
}
.list{
min-width: 400px;
max-width: 800px;
display: flex;
}
.list .item{
width: 100%;
display: flex;
}
.list .item .info{
flex:1;
border-bottom: 1px dashed #e4e4e4;
padding-bottom: 10px;
}
.list .item p{
margin: 0;
}
.list .item .name{
color: #FB7299;
font-size: 14px;
font-weight: bold;
}
.list .item .text{
color:#333;
padding: 10px 0;
}
.list .item .time{
color: #999;
font-size: 12px;
}
</style>
</head>
<body>
<!-- <input type="text"> -->
<div class="wrapper">
<i class="avater"></i>
<textarea id="tx" placeholder="发一条友善评论" rows="2" maxlength=""></textarea>
<button>发布</button>
</div>
<div class="wrapper">
<span class="total">0/200字</span>
</div>
<div class="list">
<div class="item" style="display: none;">
<i class="avatar"></i>
<div class="info">
<p class="name">清风徐来</p>
<p class="text">大家辛苦了,感谢大家的努力</p>
<p class="time">2024.01.20</p>
</div>
</div>
</div>
<script>
const tx = document.querySelector('#tx')
const total = document.querySelector('.total')
const item = document.querySelector('.item')
const text = document.querySelector('.text')
//获得焦点就显示
tx.addEventListener('focus',function(){
total.style.opacity=1
})
//失去焦点就隐藏
tx.addEventListener('blur',function(){
total.style.opacity=0
})
//检测用户输入
tx.addEventListener('input',function(){
total.innerHTML = `${tx.value.length}/200字`
})
//按下回车发布评论
tx.addEventListener('keyup',function(e){
if(e.key === 'Enter'){
//如果输入不为空就显示和打印
if(tx.value.trim() !== ''){
item.style.display = 'block'
//用户输入内容
text.innerHTML = tx.value
}
//按下回车,结束清空
tx.value = ''
//按下回车 字符统计复原
total.innerHTML = '0/200字'
}
})
</script>
</body>
</html>
环境对象
谁调用指向谁
<button>点击</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click',function(){
this.style.color = 'red'
})
</script>
回调函数
Tab栏切换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.tab{
width: 590px;
height: 340px;
margin: 20px;
border: 1px solid #e4e4e4;
}
.tab-nav{
width: 100%;
height: 60px;
line-height: 60px;
display: flex;
justify-content: space-between;
}
.tab-nav h3{
font-size: 24px;
font-weight: normal;
margin-left: 20px;
}
.tab-nav ul{
list-style: none;
display: flex;
justify-content: flex-end;
}
.tab-nav ul li{
margin: 0 20px;
font-size: 14px;
}
.tab-nav ul li a{
text-decoration: none;
border-bottom: 2px solid transparent;
color: #333;
}
.tab-nav ul li a.active{
border-color:#e1251b;
color: #e1251b;
}
.tab-content{
padding: 0 16px;
}
.tab-content .item{
display: none;
}
.tab-content .item.active{
display: block;
}
</style>
</head>
<body>
<div class="tab">
<div class="tab-nav">
<h3>每日特价</h3>
<ul>
<li><a class="active" href="javascript:;">精选</a></li>
<li><a href="javascript:;">美食</a></li>
<li><a href="javascript:;">百货</a></li>
<li><a href="javascript:;">个护</a></li>
<li><a href="javascript:;">预告</a></li>
</ul>
</div>
<div class="tab-content">
<div class="item active"><img src="./images/1.jpg" alt="" /></div>
<div class="item "><img src="./images/2.jpg" alt="" /></div>
<div class="item "><img src="./images/3.jpg" alt="" /></div>
<div class="item "><img src="./images/4.jpg" alt="" /></div>
<div class="item "><img src="./images/5.jpg" alt="" /></div>
</div>
</div>
<script>
//获取a元素
const as = document.querySelectorAll('.tab-nav a')
for(let i=0;i<=as.length;i++){
as[i].addEventListener('mouseenter',function(){
document.querySelector('.tab-nav .active').classList.remove('active')
this.classList.add('active')
document.querySelector('tab-content .active').classList.remove('active')
document.querySelector(`.tab-content .item:nth-child(${i+1})`).classList.add('active')
})
}
</script>
</body>
</html>
第三天
全选按钮案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
table{
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #c0c0c0;
width: 500px;
margin: 100px auto;
text-align: center;
}
th{
background-color: #09c;
font:bold 16px "微软雅黑";
color: #fff;
height: 24px;
}
td{
border: 1px solid #d0d0d0;
color: #404040;
padding: 10px;
}
</style>
</head>
<body>
<table>
<tr>
<th class="allCheck">
<input type="checkbox" name="" id="checkAll"><span class="all">全选</span>
</th>
<th>商品</th>
<th>商家</th>
<th>价格</th>
</tr>
<tr>
<td>
<input type="checkbox" name="check" class="ck">
</td>
<td>小米手机</td>
<td>小米</td>
<td>¥1999</td>
</tr>
<tr>
<td>
<input type="checkbox" name="" class="ck">
</td>
<td>小米净水器</td>
<td>小米</td>
<td>¥4999</td>
</tr>
<tr>
<td>
<input type="checkbox" name="check" class="ck">
</td>
<td>小米电视</td>
<td>小米</td>
<td>¥5999</td>
</tr>
</table>
<script>
//获取大复选框
const checkAll = document.querySelector('#checkAll')
//获取小复选框
const cks = document.querySelectorAll('.ck')
//点击大复选框 注册事件
checkAll.addEventListener('click',function(){
//遍历所有小复选框 让小复选框的checked=大复选框的checked
for(let i=0;i<cks.length;i++){
cks[i].checked = checkAll.checked
// cks[i].checked = this.checked 都可
//小复选框控制大复选框
for(let i = 0;i<cks.length;i++){
cks[i].addEventListener('click',function(){
//判断选中小复选框个数是不是等于总的小复选框个数
//伪类选择器
// console.log(document.querySelectorAll('.ck:checked').length === cks.length)
checkAll.checked = document.querySelectorAll('.ck:checked').length === cks.length
})
}
}
})
</script>
</body>
</html>
事件流
事件捕获
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father{
width: 500px;
height: 500px;
background-color: pink;
}
.son{
width: 200px;
height: 200px;
background-color: black;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
const fa = document.querySelector('.father')
const son = document.querySelector('.son')
document.addEventListener('click',function(){
alert('爷爷')
})
fa.addEventListener('click',function(){
alert('爸爸')
})
son.addEventListener('click',function(){
alert('儿子')
})
</script>
</body>
</html>
事件冒泡
阻止冒泡
事件解绑
鼠标经过事件
两种注册事件
事件委托
<!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>第1个孩子</li>
<li>第2个孩子</li>
<li>第3个孩子</li>
<li>第4个孩子</li>
<li>第5个孩子</li>
<p>不变色</p>
</ul>
<script>
//获得父元素
const ul = document.querySelector('ul')
ul.addEventListener('click',function(e){
// alert(11)
// e.target.style.color='red'
//只有li有效果
if(e.target.tagName === 'LI'){
e.target.style.color='red'
}
})
</script>
</body>
</html>
tab栏切换案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.tab{
width: 590px;
height: 340px;
margin: 20px;
border: 1px solid #e4e4e4;
}
.tab-nav{
width: 100%;
height: 60px;
line-height: 60px;
display: flex;
justify-content: space-between;
}
.tab-nav h3{
font-size: 24px;
font-weight: normal;
margin-left: 20px;
}
.tab-nav ul{
list-style: none;
display: flex;
justify-content: flex-end;
}
.tab-nav ul li{
margin: 0 20px;
font-size: 14px;
}
.tab-nav ul li a{
text-decoration: none;
border-bottom: 2px solid transparent;
color: #333;
}
.tab-nav ul li a.active{
border-color:#e1251b;
color: #e1251b;
}
.tab-content{
padding: 0 16px;
}
.tab-content .item{
display: none;
}
.tab-content .item.active{
display: block;
}
</style>
</head>
<body>
<div class="tab">
<div class="tab-nav">
<h3>每日特价</h3>
<ul>
<li><a class="active" href="javascript:;" data-id="0">精选</a></li>
<li><a href="javascript:;" data-id="1">美食</a></li>
<li><a href="javascript:;" data-id="2">百货</a></li>
<li><a href="javascript:;" data-id="3">个护</a></li>
<li><a href="javascript:;" data-id="4">预告</a></li>
</ul>
</div>
<div class="tab-content">
<div class="item active"><img src="./images/1.jpg" alt="" /></div>
<div class="item "><img src="./images/2.jpg" alt="" /></div>
<div class="item "><img src="./images/3.jpg" alt="" /></div>
<div class="item "><img src="./images/4.jpg" alt="" /></div>
<div class="item "><img src="./images/5.jpg" alt="" /></div>
</div>
</div>
<script>
/* //获取a元素
const as = document.querySelectorAll('.tab-nav a')
for(let i=0;i<=as.length;i++){
as[i].addEventListener('mouseenter',function(){
document.querySelector('.tab-nav .active').classList.remove('active')
this.classList.add('active')
document.querySelector('tab-content .active').classList.remove('active')
document.querySelector(`.tab-content .item:nth-child(${i+1})`).classList.add('active')
})
} */
//采取事件委托的形式 tab栏切换
//获取ul父元素 因为ul只有一个
const ul = document.querySelector('.tab-nav ul')
//或者
//获取5个item
const items = document.querySelectorAll('.tab-content .item')
//添加事件
ul.addEventListener('click',function(e){
//e.target是我们点击的对象
//e.target.tagName点击那个对象的 标签名
if(e.target.tagName === 'A'){
// console.log('选的a')
//排他思想,先排除原来的active
document.querySelector('.tab-nav .active').classList.remove('active')
//当前元素添加active 是e.target
//this 指向ul 不能用this
e.target.classList.add('active')
//下面大盒子模块
const i = +e.target.dataset.id
//排他思想 先移除原来的active
document.querySelector('.tab-content .active').classList.remove('active')
//对应的大盒子 添加active
// document.querySelector(`.tab-content .item:nth-child(${i+1})`).classList.add('active')
//或者
items[i].classList.add('active')
}
})
</script>
</body>
</html>
阻止默认行为
页面加载事件
js代码写在上面时要加下面的话
页面滚动事件
电梯导航栏案例
<script>
const elevator = document.querySelector('.xtx-elevator')
//页面滚动大于300像素就显示
//添加滚动事件
window.addEventListener('scroll',function(){
const n = document.documentElement.scrollTop
if(n>=300){
elevator.style.opacity = 1
}else{
elevator.style.opacity = 0
}
//也可以用三元
//elevator.style.opacity = n >=300?1:0
})
//点击回到顶部
const backTop = document.querySelector('#backTop')
backTop.addEventListener('click',function(){
document.documentElement.scrollTop = 0
//也可以直接定位
//window.scrollTo(0,0)
})
</script>
页面尺寸事件
固定头部案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.content{
overflow: hidden;
width: 1000px;
height: 3000px;
background-color: pink;
margin: 0 auto;
}
.backtop{
display: none;
width: 50px;
left:50%;
margin: 0 0 0 505px;
position: fixed;
bottom: 60px;
z-index: 100;
}
.backtop a{
height: 50px;
width: 50px;
background: url(./images/2.jpg) 0 -600px no-repeat;
opacity: 0.35;
overflow:hidden;
display: block;
text-indent: -999em;
cursor: pointer;
}
.header{
position: fixed;
top:-80px;
left:0;
width: 100%;
height: 80px;
background-color: purple;
text-align: center;
color: #fff;
line-height: 80px;
font-size: 30px;
transition: all .3s;
}
.sk{
width: 300px;
height: 300px;
background-color: skyblue;
margin-top: 500px;
}
</style>
</head>
<body>
<div class="header">顶部导航栏</div>
<div class="content">
<div class="sk">秒杀模块</div>
</div>
<div class="backtop">
<img src="./images/1.jpg" alt="">
<a href="javascript:;"></a>
</div>
<script>
const sk = document.querySelector('.sk')
const header = document.querySelector('.header')
//页面滚动事件
window.addEventListener('scroll',function(){
//当页面滚动到秒杀模块时就改变头部的top值
//页面被卷去的头部>=秒杀模块的位置offsetTop
const n = document.documentElement.scrollTop
header.style.top = n >= sk.offsetTop ?0:'-80px'
})
</script>
</body>
</html>
电梯导航模块
<script>
const elevator = document.querySelector('.xtx-elevator')
//页面滚动大于300像素就显示
//添加滚动事件
window.addEventListener('scroll',function(){
const n = document.documentElement.scrollTop
// if(n>=300){
// elevator.style.opacity = 1
// }else{
// elevator.style.opacity = 0
// }
elevator.style.opacity = n >=300?1:0
})
//点击回到顶部
const backTop = document.querySelector('#backTop')
backTop.addEventListener('click',function(){
// document.documentElement.scrollTop = 0
//也可以直接定位
window.scrollTo(0,0)
})
(function(){
const list = document.querySelector('.xtx-elevator-list')
list.addEventListener('click',function(e){
if(e.target.tagName === 'A' && e.target.dataset.name){
const old = document.querySelector('.xtx-elevator-list .active')
if(old) old.classList.remove('active')
e.target.classList.add('active')
const top = document.querySelector(`.xtx_goods_${e.target.dataset.name}`).offsetTop
document.documentElement.scroll = top
}
})
})
</script>
页面滚动
//css
html{
scroll-behavior:smooth;
}
属性选择器
第四天
实例化对象
显示格式化时间案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<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>
</html>
时间另外一种写法
时间戳
倒计时效果案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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;
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年1月23日</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>
function getCountTime(){
//得到当前时间戳
const now = +new Date()
//得到将来时间戳
const last = +new Date('2024-2-1 00:00:00')
//得到剩余时间戳 count 记得转换为秒
const count = (last - now)/1000
// console.log(count)
//计算公式
// 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)
//把时分秒写到盒子里
const hour = document.querySelector('#hour')
const minutes = document.querySelector('#minutes')
const scond = document.querySelector('#scond')
hour.innerHTML = h
minutes.innerHTML = m
scond.innerHTML = s
}
//先调用一次
getCountTime()
//开启定时器
setInterval(getCountTime,1000)
</script>
</body>
</html>
DOM节点
点击关闭案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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>
<div class="box1">X</div>
<script>
const box1 = document.querySelector('.box1')
// const box = document.querySelector('.box')
box1.addEventListener('click',function(){
this.parentNode.style.display='none'
})
</script>
</body>
</html>
节点操作
增加节点
删除节点
M端事件
插件
下载
把css和js代码文件直接复制到自己文件目录下
再去演示里找自己喜欢的,查看源代码,直接复制粘贴
查看再js文件中哪个位置,再引入
再自己修改调整成自己想要的
补充我的收藏夹:
学生信息表案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</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 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 = []
//录入模块 表单提交事件
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)
//清空表单 重置
this.reset()
//调用渲染函数
render()
})
//渲染函数
function render(){
//先清空tbody,把最新数组里面的数据渲染完毕
tbody.innerHTML = ''
//遍历数组
for(let i = 0;i< arr.length;i++){
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)
}
}
//删除
tbody.addEventListener('click',function(e){
if(e.target.tagName === 'A'){
//得到当前元素的自定义属性 data-id
//删除arr 数组里面对应的数据
arr.splice(e.target.dataset.id,1)
console.log(arr)
//从新渲染一次
render()
}
})
</script>
</body>
</html>
第五天
BOM浏览器对象模型
定时器-延时函数
延时函数:执行一次
间歇函数:每隔一段时间就执行一次,除非手动清除
5秒自动消失广告案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img{
position: fixed;
left: 0;
bottom: 0;
}
</style>
</head>
<body>
<img src="./images/1.jpg" alt="">
<script>
const img = document.querySelector('img')
setTimeout(function(){
img.style.display = 'none'
},3000)
</script>
</body>
</html>
js执行机制
或者1243
location对象
5秒自动跳转页面案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
span{
color: red;
}
</style>
</head>
<body>
<a href="http://www.itcast.cn">支付成功<span>5</span>秒钟之后跳转到首页</a>
<script>
const a = document.querySelector('a')
//开启定时器
//声明倒计时变量
let num = 5
let timerId=setInterval(function(){
num--
a.innerHTML = `支付成功<span>${num}</span>秒钟之后跳转到首页`
//如果num===0 则停止定时器,并且完成跳转功能
if(num === 0){
clearInterval(timerId)
//跳转
location.href = 'http://www.itcast.cn'
}
},1000)
</script>
</body>
</html>
方法
navigator对象
自动跳转到移动端
<script>
!(function(){
const userAgent = navigator.userAgent
const android = userAgent.match(/(Android);?[\s\/]+([\d.]+)?/)
const iphone = userAgent.match(/(iPhone\sOS)\s([\d_]+)/)
if(android || iphone){
location.href = 'http://m.itcast.cn'
}
})();
</script>
histroy对象
本地存储
本地存储复杂数据类型
转换为JSON字符串存储
<script>
const obj = {
uname:'pink老师',
age:18,
gender:'女'
}
localStorage.setItem('obj',JSON.stringify(obj))
</script>
map方法join方法
<script>
//数组map方法 处理数据 并且返回一个数组
const arr = ['red','blue','pink']
const newArr = arr.map(function(ele,index){
return ele + '颜色'
})
console.log(newArr)
//join方法 把数组转换为字符串
//小括号为空则逗号分割
console.log(newArr.join())
//小括号是空字符串,则元素之间没有分隔符
console.log(newArr.join(''))
console.log(newArr.join('|'))
</script>
学生就业信息表案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</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>
<div class="title">共有数据<span>0</span>条</div>
<table>
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>薪资</th>
<th>就业城市</th>
<th>操作</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
const initData = [
{
stuId :1,
uname:'对对对',
age:22,
gender:'女',
salary:'12000',
city:'北京',
time:'2024/1/1 11:11:11'
}
]
// localStorage.setItem('data',JSON.stringify(initData))
const arr = JSON.parse(localStorage.getItem('data')) || []
console.log(arr)
const tbody = document.querySelector('tbody')
function render(){
const trArr = arr.map(function(ele,index){
return`
<tr>
<td>${ele.stuId}</td>
<td>${ele.uname}</td>
<td>${ele.age}</td>
<td>${ele.gender}</td>
<td>${ele.salary}</td>
<td>${ele.city}</td>
<td>${ele.time}</td>
<td>
<a href = "javascript:" data-id="${index}">
<i class="iconfont icon-shanchu"></i>
删除
</a>
</td>
</tr>
`
})
console.log(trArr)
tbody.innerHTML = trArr.join('')
document.querySelector('.title span').innerHTML = arr.length
}
render()
//新增业务
const info = document.querySelector('.info')
const uname = document.querySelector('.uname')
const age = document.querySelector('.age')
const salary = document.querySelector('.salary')
const gender = document.querySelector('.gender')
const city = document.querySelector('.city')
//form表单注册提交事件,阻止默认行为
info.addEventListener('submit',function(e){
e.preventDefault()
//非空判断
if(!uname.value || !age.value || !salary.value){
return alert('输入内容不能为空')
}
arr.push({
stuId:arr.length?arr[arr.length-1].stuId+1 : 1,
uname:uname.value,
age:age.value,
salary:salary.value,
gender:gender.value,
city:city.value,
time:new Date().toDateString()
})
render()
//重置表单
this.reset()
//把数组重新存入本地存储里面
localStorage.setItem('data',JSON.stringify(arr))
})
//删除模块
//采用事件委托形式,给tbody注册点击事件
tbody.addEventListener('click',function(e){
//判断是否点击的是删除按钮 A 链接
if(e.target.tagName === 'A'){
// alert(11)
//得到当前点击链接的索引号,渲染数据的时候,动态给a链接添加自定义属性
console.log(e.target.dataset.id)
//确认是否真的删除
if(confirm('你真的要删除这条数据嘛')){
//根据索引号 利用splice 删除数组这条数据
arr.splice(e.target.dataset.id,1)
//重新渲染
render()
//把最新arr数组存入本地存储
localStorage.setItem('data',JSON.stringify(arr))
}
}
})
</script>
</body>
</html>
第六、七天
正则表达式
定义正则表达式
检测查找是否匹配
<script>
const str = '学习前端'
//定义规则
const reg = /前端/
//是否匹配
// console.log(reg.test(str))
//exec() 返回数组
console.log(reg.exec(str))
</script>
元字符
边界符
量词
字符类
输入用户名案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
span{
display: inline-block;
width: 250px;
height: 30px;
vertical-align: middle;
line-height: 30px;
padding-left: 15px;
}
.error{
color: red;
background-color: url(./images/1.jpg) no-repeat left center;
}
.right{
color: green;
background: url(./images/2.jpg) no-repeat left center;
}
</style>
</head>
<body>
<input type="text">
<span></span>
<script>
const reg = /^[a-zA-Z0-9-_]{6,16}/
const input = document.querySelector('input')
const span = input.nextElementSibling
input.addEventListener('blur',function(){
if(reg.text(this.value)){
span.innerHTML='输入正确'
span.className = 'right'
}else{
span.innerHTML = '请输入6-16位英文数字下划线'
span.className = 'error'
}
})
</script>
</body>
</html>
修饰符
过滤敏感词案例
<!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>
<textarea name="" id="" cols="30" row="10"></textarea>
<button>发布</button>
<div></div>
<script>
const tx = document.querySelector('textarea')
const btn = document.querySelector('button')
const div = document.querySelector('div')
btn.addEventListener('click',function(){
div.innerHTML = tx.value.replace(/激情|基情/g,'**')
tx.value = ''
})
</script>
</body>
</html>
页面注册案例
<script>
(function(){
//发送短信验证码模块
const code = document.querySelector('.code')
let flag = true//通过一个变量来控制
//点击事件
code.addEventListener('click',function(){
if(flag){
//取反不能马上二次点击
flag=false
let i = 5
//点击完之后立马触发
code.innerHTML=`0${i}秒后重新获取`
let timeId = setInterval(function(){
i--
code.innerHTML = `0${i}秒后重新获取`
if(i === 0){
clearInterval(timeId)
//重新获取
code.innerHTML = `重新获取`
//到时间开启flag
flag=true
}
},1000)
}
})
})();
//验证用户名
const username = document.querySelector('[name=username]')
//使用change事件 值发生变化的时候
username.addEventListener('change',verifyName)
//封装函数
function verifyName(){
const span = username.nextElementSibling
//定规则
const reg = /^[a-zA-Z0-9-_]{6,10}$/
if(!reg.test(username.value)){
span.innerText = '输入不合法,请输入6-10位'
return false
}
//合法的
span.innerText = ''
return true
}
//验证手机号
const phone = document.querySelector('[name=phone]')
//使用change事件 值发生变化的时候
phone.addEventListener('change',verifyPhone)
//封装函数
function verifyPhone(){
const span = phone.nextElementSibling
//定规则
const reg = /^1(3\d|4[5-9]5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
if(!reg.test(phone.value)){
span.innerText = '输入不合法,请输入正确11位手机号码'
return false
}
//合法的
span.innerText = ''
return true
}
//验证验证码
const codeInput= document.querySelector('[name=code]')
//使用change事件 值发生变化的时候
codeInput.addEventListener('change',verifyCode)
//封装函数
function verifyCode(){
const span = codeInput.nextElementSibling
//定规则
const reg = /^\d{6}$/
if(!reg.test(codeInput.value)){
span.innerText = '输入不合法,请输入6位数字'
return false
}
//合法的
span.innerText = ''
return true
}
//验证密码框
const password= document.querySelector('[name=password]')
//使用change事件 值发生变化的时候
password.addEventListener('change',verifyPwd)
//封装函数
function verifyPwd(){
const span = password.nextElementSibling
//定规则
const reg = /^[a-zA-Z0-9-_]{6,20}$/
if(!reg.test(password.value)){
span.innerText = '输入不合法,请输入6-20位数字字母符号组成'
return false
}
//合法的
span.innerText = ''
return true
}
//密码再次认证
const confirm= document.querySelector('[name=confirm]')
//使用change事件 值发生变化的时候
confirm.addEventListener('change',verifyConfirm)
//封装函数
function verifyConfirm(){
const span = confirm.nextElementSibling
if(confirm.value!==password.value){
span.innerText = '两次密码输入不一致'
return false
}
//合法的
span.innerText = ''
return true
}
//我同意模块
const queren = document.querySelector('.icon-queren')
queren.addEventListener('click',function(){
//切换类 原来有的就删掉,原来没有就添加
this.classList.toggle('icon-queren2')
})
//提交模块
const form = document.querySelector('form')
form.addEventListener('submit',function(e){
if(!queren.classList.contains('icon-queren2')){
alert('请勾选同意协议')
//阻止提交
e.preventDefault()
}
//判断上面每个框框是否通过,只要有一个没有通过就阻止
if(!verifyName()) e.preventDefault()
if(!verifyPhone()) e.preventDefault()
if(!verifyCode()) e.preventDefault()
if(!verifyPwd()) e.preventDefault()
if(!verifyConfirm()) e.preventDefault()
})
</script>
登录页面案例
<script>
//tab栏切换 事件委托
const tab_nav = document.querySelector('.tab-nav')
const pane = document.querySelectorAll('.tab-pane')
//事件监听
tab_nav.addEventListener('click',function(e){
if(e.target.tagName === 'A'){
//取消上一个active
tab_nav.querySelector('.active').classList.remove('active')
//当前元素添加active
e.target.classList.add('active')
//先干掉所有人 for循环
for(let i =0 ;i<pane.length;i++){
pane[i].style.display='none'
}
//让对应序号的 大pane显示
pane[e.target.dataset.id].style.display='block'
}
})
//点击提交模块
const form = document.querySelector('form')
const agree = document.querySelector('[name=agree]')
const username = document.querySelector('[name=username]')
form.addEventListener('submit',function(e){
e.preventDefault()
if(!agree.checked){
return alert('请勾选同意协议')
}
//记录用户名到本地存储
localStorage.setItem('xtx-uname',username.value)
//跳转到首页
location.href = './index.html'
})
</script>
<script>
//获取第一个小li
const li1 = document.querySelector('.xtx_navs li:first-child')
const li2 = li1.nextElementSibling
//最好做个渲染函数 因为退出登录需要重新渲染
function render(){
//读取本地存储的用户名
const uname = localStorage.getItem('xtx-uname')
if(uname){
li1.innerHTML = `<a href = "javascript:;"><i class= "iconfont icon-user">${uname}</i></a>`
li2.innerHTML = `<a href="javascript:;">退出登录</a>`
}else{
li1.innerHTML = '<a href ="./login.html">请先登录</a>'
li2.innerHTML = '<a href ="./register.html">免费注册</a>'
}
}
render()
//点击退出登录模块
li2.addEventListener('click',function(){
//删除本地存储的数据
localStorage.removeItem('xtx-uname')
//重新渲染
render()
})
</script>
放大镜效果
<script>
const small = document.querySelector('.small')
const middle = document.querySelector('.middle')
const large = document.querySelector('.large')
//事件委托
small.addEventListener('mouseover',function(e){
if(e.target.tagName === 'IMG'){
//排他 干掉以前的active li 上面
this.querySelector('.active').classList.remove('active')
//当前元素的爸爸添加 active
e.target.parentNode.classList.add('active')
//让中等盒子里面的图片 src更换为 小图片src
middle.querySelector('img').src = e.target.src
//大盒子更换背景图片
large.style.backgroundImage =`url(${e.target.src})`
}
})
//鼠标经过中等盒子 显示隐藏大盒子
middle.addEventListener('mouseenter',show)
middle.addEventListener('mouseleave',hide)
let timeId = null
//显示函数 显示大盒子
function show(){
clearTimeout(timeId)
large.style.display = 'block'
}
//隐藏函数 隐藏大盒子
function hide(){
timeId = setTimeout(function(){
large.style.display = 'none'
},200)
}
// 鼠标经过大盒子 显示隐藏 大盒子
large.addEventListener('mouseenter',show)
large.addEventListener('mouseleave',hide)
//鼠标经过中等盒子,显示隐藏 黑色遮罩层
const layer = document.querySelector('.layer')
middle.addEventListener('mouseenter',function(){
layer.style.display = 'block'
})
middle.addEventListener('mouseleave',function(){
layer.style.display = 'none'
})
//移动黑色遮罩盒子
middle.addEventListener('mousemove',function(e){
let x = e.pageX - middle.getBoundingClientRect().left
let y = e.pageY - middle.getBoundingClientRect().top-document.documentElement.scrollTop
//黑色遮罩移动 再middle盒子内 限定移动的距离
if(x>=0&&x<=400&&y>=0&&y<=400){
let mx = 0,my = 0
if(x<100) mx = 0
if(x>=100&&x<=300)mx = x-100
if(x>300)mx=200
if(y<100) my = 0
if(y>=100&&y<=300)my = y-100
if(y>300)my=200
layer.style.left=mx+'px'
layer.style.top=my+'px'
//大盒子的背景图片要跟随中等盒子移动 存在的关系是2倍
large.style.backgroundPositionX=-2*mx+'px'
large.style.backgroundPositionY=-2*my+'px'
}
})
</script>