回到顶部按钮
子组件定义:
style样式
<style>
#topBlock {
color:#fff;
font-size: 0.6rem;
text-align: center;
line-height: 3rem;
width:3rem;
height:3rem;
position: fixed;
right: 2%;
bottom: 23%;
border-radius: 50%;
z-index: 100;
}
</style>
html结构
<template>
<div id="topBlock" @click="srcollTop">
![](logo.png)
</div>
</template>
js内容
<script>
export default {
mounted:function () {
},
methods: {
srcollTop: function () {
var timer = null;
timer = setInterval(function () { //设置一个计时器
var curTop =document.body.scrollTop; //获取距离顶部的距离
var ct;
if(curTop==0){
document.getElementById('scrollBar').scrollTop=0//移动到顶部
clearInterval(timer);//清除计时器
}else{
ct=curTop;
ct -= 50;
if (ct > 0) {//如果与顶部的距离大于零
window.scrollTo(0, ct);//向上移动50px
} else {//如果距离小于等于零
window.scrollTo(0, 0);//移动到顶部
clearInterval(timer);//清除计时器
}
}
}, 10);//隔10ms执行一次前面的function,展现一种平滑滑动效果
}
}
}
</script>
父组件引用:
html内容
<topTop v-if="topFlag"></topTop>
js内容
methods: {
topAppear:function(){
var self=this;
document.getElementById('scrollBar').onscroll = function(){
var h = document.getElementById('scrollBar').scrollTop;
var deviceHeight=document.documentElement.clientHeight;//屏幕高度
var elHeight=document.getElementById('scrollBar').scrollHeight;//可滚动的范围
if (h+deviceHeight+50>=elHeight) {
var pagesize=10;
if(self.limitRush){
self.limitRush=false;
self.getInitProd(pagesize,self.pageno);
}
}else if(h>deviceHeight+200){
self.topFlag=true;
}else if(h<deviceHeight){
self.topFlag=false;
}
};
}
}