<!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>
//css部分
*{
margin: 0;
padding: 0;
}
//让网页足够长出现滚动条
body{
width: 100%;
height: 3000px;
background-color: aquamarine;
}
//一键回到顶部的按钮,初始为隐藏
.box{
width: 20px;
height: 20px;
position: fixed;
right: 100px;
bottom: 100px;
background-color: black;
display: none;
/* transition: top 0.5s linear; */
}
//顶部通栏 初始隐藏在窗口上面
.dingbu{
width: 100%;
height: 80px;
background-color: beige;
position: fixed;
top: -80px;
transition: top 0.5s linear;
}
</style>
</head>
<body>
<input class="box" ></input>
<div class="dingbu"></div>
//js部分
<script>
// 获取元素
var dingbu=document.querySelector('.dingbu');
var box=document.querySelector('.box');
// 滚动事件
window.οnscrοll=function(){
// 获取滚动 卷曲的高度
var height=document.documentElement.scrollTop||document.body.scrollTop;
console.log(height);
//判断是否卷曲超过500px超过显示通栏 显示按钮否则不显示
if(height>500)
{
dingbu.style.top='0px';
box.style.display='block';
}else
{
dingbu.style.top='-80px';
box.style.display='none';
}
}
//给按钮添加点击事件点击后利用window.scrollTo({})方法实现
box.οnclick=function(){
window.scrollTo({
top:0,
left:0,
behavior: "smooth"
});
}
</script>
</body>
</html>
关于window.scrollTo方法的使用
window.scrollTo({
top:0,
left:0,
behavior: "smooth"
});
behavior的参数
1.smooth 匀速滑动到目标位置
2.instant 瞬间滚到目标位置