使用原生的js实现点击滚动条回到顶部并且有过渡效果
废话不多说,上代码!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 100px;
height: 100px;
background-color: red;
position: fixed;
bottom: 20px;
right: 0;
font-size: 40px;
padding-left: 10px;
cursor: pointer;
line-height: 50px;
display: none;
}
/* *{
scroll-behavior: smooth;
} */
</style>
</head>
<body>
<div>点击上移</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<script>
let oDiv = document.querySelector("div")
window.addEventListener("scroll", (e)=>{
let pos = document.documentElement.scrollTop
if(pos < 100){
oDiv.style.display = "none";
}else{
oDiv.style.display = "block";
}
})
oDiv.addEventListener("click", (e)=>{
let clock = setInterval(()=>{
if(document.documentElement.scrollTop!=0){
document.documentElement.scrollTop -= 100;
}else{
clearInterval(clock);
}
},10)
})
</script>
</body>
</html>
如果帮到你了记得点个赞!