1回到底部
<template>
<div class="totop">
<!-- 自定义图片 -->
<div class="btnTop" v-if="btnFlag" @click="backTop()">
<img src="../assets/logo.png" alt="" class="imga" />
</div>
</div>
</template>
<script>
export default {
name: "totop",
data() {
return {
btnFlag: false,
};
},
// 利用VUE写一个在控制台打印当前的scrollTop。首先,在 mounted 钩子中给window添加一个滚动滚动监听事件
mounted() {
window.addEventListener("scroll", this.scrollToTop);
},
destroyed() {
window.removeEventListener("scroll", this.scrollToTop);
},
methods: {
// 点击图片回到顶部方法,加计时器是为了过渡顺滑
backTop() {
let that = this;
let timer = setInterval(() => {
let ispeed = Math.floor(-that.scrollTop / 5);
document.documentElement.scrollTop = document.body.scrollTop =
that.scrollTop + ispeed;
if (that.scrollTop === 0) {
clearInterval(timer);
}
}, 16);
},
// 监听回到顶部按钮距浏览器顶部的距离,滚动的距离如果大于浏览器高度时,设置 btnFlag 为true,否则就是false
scrollToTop() {
let that = this;
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
that.scrollTop = scrollTop;
//为了计算距离顶部的高度,当高度大于50显示回顶部图标,小于50则隐藏
if (that.scrollTop > 50) {
that.btnFlag = true;
} else {
that.btnFlag = false;
}
},
},
};
</script>
<style lang="scss" scoped>
.totop {
position: fixed;
right: 40px;
bottom: 60px;
width: 50px;
height: 50px;
padding: 10px;
cursor: pointer;
}
.imga {
position: relative;
top: -20px;
border: 3px solid #000;
width: 50px;
height: 50px;
}
</style>
使用:
1定义组件,代码如上
2 引入即可
2 吸顶
ref="header" :class="headerFixed ? 'issFixed' : ''"
<template>
<div class="home">
<div ref="header" class="header-bg" :class="headerFixed ? 'issFixed' : ''">
Header
</div>
<div style="height: 500px">111</div>
<div style="height: 300px">222</div>
<div style="height: 300px">222</div>
<div style="height: 300px">222</div>
<div style="height: 300px">222</div>
<div style="height: 300px">222</div>
<div style="height: 300px">222</div>
<div style="height: 300px">222</div>
<div style="height: 300px">222</div>
<div>333</div>
</div>
</template>
<script>
export default {
name: "home",
data() {
return {
offsetTop: 0,
offsetHeight: 0,
headerFixed: 0,
};
},
mounted() {
this.$nextTick(() => {
// 获取吸顶元素的dom
let header = this.$refs.header;
// 吸顶元素到top的距离
this.offsetTop = header.offsetTop;
// 元素自身的高度
this.offsetHeight = header.offsetHeight;
// 监听滚动条
window.addEventListener("scroll", this.handleScroll);
});
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll() {
// 得到页面滚动的距离,兼容写法
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
// 判断页面滚动的距离是否大于吸顶元素的位置
this.headerFixed = scrollTop > this.offsetTop - this.offsetHeight;
},
},
};
</script>
<style>
.issFixed {
position: fixed;
top: 0px;
left: 0px;
right: 0px;
z-index: 4;
}
.header-bg {
font-size: 30px;
background-color: red;
}
</style>