<!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>
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 3000px;
}
.topBar {
width: 100%;
height: 50px;
line-height: 50px;
text-align: center;
color: #fff;
background-color: skyblue;
position: fixed;
font-size: 30px;
left: 0;
top: 0;
display: none;
}
.topBar.active {
display: block;
}
.goTop {
width: 50px;
height: 50px;
line-height: 25px;
font-size: 20px;
color: #fff;
background-color: pink;
position: fixed;
bottom: 50px;
right: 50px;
text-align: center;
cursor: pointer;
opacity: 0;
transition: opacity .5s linear;
}
.goTop.active {
opacity: 1;
}
</style>
</head>
<body>
<div class="topBar">顶部通栏</div>
<div class="goTop">回到顶部</div>
<script>
/*
作业: 回到顶部
代码实现:
1. 获取元素
=> 顶部通栏
=> 回到顶部按钮
2. 操作两个盒子显示和隐藏
=> 使用 window.onscroll 事件
=> 再事件里面随时获取浏览器卷去的高度
=> 通过卷去的高度判断(自己定一个边界值)
=> 操作显示
-> 添加类名 active
=> 操作隐藏
-> 取消类名 active
=> 用哪种方式添加和取消
1. className - 好加不好去
2. classList - 随便
3. 点击回到顶部按钮的时候, 滚动条回到顶部
=> 给 goTop 按钮绑定一个点击事件
=> 再事件处理函数里面使用 scrollTo()
*/
// 1. 获取元素
var topBar = document.querySelector('.topBar')
var goTop = document.querySelector('.goTop')
// 2. 操作两个盒子显示隐藏
window.onscroll = function () {
// 2-2. 获取浏览器卷去的高度
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
// 2-3. 自己定一个边界值进行判断(300)
if (scrollTop >= 300) {
// 两个盒子显示
// className
// topBar.className = 'topBar active'
// goTop.className = 'goTop active'
// classList
topBar.classList.add('active')
goTop.classList.add('active')
} else {
// 两个盒子隐藏
// topBar.className = 'topBar'
// goTop.className = 'goTop'
topBar.classList.remove('active')
goTop.classList.remove('active')
}
}
// 3. 回到顶部
goTop.onclick = function () {
window.scrollTo({
top: 0,
behavior: 'smooth'
})
}
</script>
</body>
</html>
带有添加和删除功能的表格
最新推荐文章于 2021-07-28 19:41:55 发布