<!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>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 2000px;
}
.banner {
width: 100%;
height: 0px;
background-color: pink;
position: fixed;
top: 0;
left: 0;
font-size: 30px;
display: flex;
justify-content: center;
align-items: center;
color: aliceblue;
overflow: hidden;
transition: height .5s linear;
}
.btn {
width: 100px;
height: 50px;
background-color: aqua;
color: azure;
display: flex;
justify-content: center;
align-items: center;
position: fixed;
right: 20px;
bottom: 20px;
}
</style>
</head>
<body>
<div class="banner">我是顶部通栏</div>
<button class="btn" style="display: none;">返回顶部</button>
<script>
var banner = document.querySelector('.banner')
var btn = document.querySelector('.btn')
// window.onscroll 滚动条事件
window.onscroll = function () {
//window.scrollY 滚动条纵轴
if (window.scrollY > 500) {
// 出现顶部通栏 返回顶部按钮
banner.style.height = "80px"
btn.style.display = "block"
} else {
//隐藏顶部通栏 返回顶部按钮
banner.style.height = "0px"
btn.style.display = "none"
}
}
//点击按钮返回顶部
btn.onclick = function () {
// setInterval 周期性定时器
var timer = setInterval(function () {
// document.documentElement.scrollTop 获取或设置一个元素的内容垂直滚动的像素数
if (document.documentElement.scrollTop > 0) {
document.documentElement.scrollTop -=100
} else {
document.documentElement.scrollTop = 0
// clearInterval 清除定时器
clearInterval(timer)
}
},
40
)
}
</script>
</body>
</html>
JS:BOM应用_随着滚动条出现顶部通栏、返回顶部按钮
最新推荐文章于 2024-05-10 10:16:57 发布