原生版本
<!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>
body{
height: 100rem;
}
html{
scroll-behavior: smooth;
}
button{
position: fixed;
bottom: 20px;
left: 25px;
opacity: 0;
transition: all .5s;
}
</style>
</head>
<body>
<button>^</button>
<script>
const button = document.querySelector("button")
button.addEventListener("click" ,()=>{
window.scrollTo(0,0)
})
window.addEventListener("scroll",()=>{
let html = document.documentElement;
if(html.scrollTop>1){
button.style.opacity = 1
}else
button.style.opacity = 0
})
</script>
</body>
vue版本
<el-button
class="toTop"
:class="{ active: !show }"
@click="toTopBar"
>
<i class="el-icon-arrow-up"></i>
</el-button>
<script>
export default {
data() {
return {
show: false,
};
},
methods: {
toTopBar() {
window.scrollTo(0, 0);
},
},
mounted() {
window.addEventListener("scroll", () => {
let html = document.documentElement;
if (html.scrollTop > 1)
this.show = true;
else
this.show = false;
});
},
}
</sctipt>
<style>
html {
scroll-behavior: smooth;
}
.toTop {
transition: all 0.5s;
}
.active {
opacity: 0;
}
</style>
//返回至顶部
window.scrollTo(0,0)
vue版本的实现流程
//平滑滚动 !加在html上(全局生效),加在其他地方其他无效,因为是对窗口的滑动?滚动条在页面上?
html{
scroll-behavior: smooth;
}
//返回顶部后消失+滚动一定距离出现 在挂载后(mounted)中调用
window.addEventListener("scroll",()=>{
let html=document.documentElement;
if(html.scrollTop > 1)
this.show = true;
else
this.show = false;
})
//渐隐渐现的过渡效果
.active{
opacity: 0;
}