vue 返回顶部
<div class="go-top">
<button @click="goTop" ref="btn" title="回到顶部">
<i class="iconfont icongoTop"></i>
</button>
</div>
let timer = null;
data() {
return {
isTop: true
};
},
watch: {},
mounted: function() {
this.needScroll();
},
methods: {
needScroll() {
let clientHeight = document.documentElement.clientHeight;
let obtn = this.$refs.btn;
window.onscroll = function () {
let osTop = document.documentElement.scrollTop || document.body.scrollTop
console.log(osTop,clientHeight/3);
if (osTop >= clientHeight/3) {
obtn.style.display = 'block'
} else {
obtn.style.display = 'none'
}
if (!this.isTop) {
clearInterval(this.timer)
}
this.isTop = false
}
},
goTop() {
timer = setInterval(function() {
let osTop =
document.documentElement.scrollTop || document.body.scrollTop;
let ispeed = Math.floor(-osTop / 5);
document.documentElement.scrollTop = document.body.scrollTop =
osTop + ispeed;
this.isTop = true;
if (osTop === 0) {
clearInterval(timer);
}
}, 30);
}
},
.go-top {
width: 100%;
button {
width: 50px;
height: 50px;
border-radius: 50%;
position: fixed;
right: 40px;
bottom: 100px;
border: none;
display: none;
i{
font-size: 0.6rem;
}
}
}
//谨记一 检查父级高度是否有限制
//谨记二 检查父级 overflow: hidden;是否有限制