HTML code
<template>
<div>
<a href="#top" target="_self" id="top-btn">
<img src="/images/返回顶部.png" alt />
</a>
</div>
</template>
Icons are in the Alibaba Vector Icon Library: iconfont-Alibaba Vector Icon Library Enter "back to top" to search
Add a scrolling listener event to the window in the mounted hook
mounted() {
window.addEventListener("scroll", this.scrollToTop);
},
Then in the method, add this scrollToTop method
scrollToTop() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop ||
document.body.scrollTop;
console.log('距离顶部的距离:'+scrollTop)
}
Monitor the distance from the back to top button to the top of the browser. If the scrolling distance is greater than the height of the browser, set toTop to true, otherwise it is false
scrollToTop() {
let topBtn = document.getElementById("top-btn");
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
console.log("距离顶部的距离:" + scrollTop);
let browserHeight = window.outerHeight;
//这里也可以个值距离的数值
if (scrollTop > browserHeight) {
topBtn.style.display = "block";
} else {
topBtn.style.display = "none";
}
},
To leave the page, you need to remove the monitored event, otherwise an error will be reported
destroyed() {
window.removeEventListener("scroll", this.scrollToTop);
},
HTML code
#to-top-btn {
width: 2.4rem;
height: 2.4rem;
position: fixed !important;
top: 30rem;
right: 0.2rem;
display: none;
}
#to-top-btn img {width: 100%;}
Renderings:
Full code:
<template>
<div>
<a href="#top" target="_self" id="to-top-btn">
<img src="/images/返回顶部.png" alt />
</a>
</div>
</template>
<script>
export default {
data() {
return {
};
},
mounted() {
window.addEventListener("scroll", this.scrollToTop);
},
methods: {
scrollToTop() {
let topBtn = document.getElementById("to-top-btn");
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
console.log("距离顶部的距离:" + scrollTop);
let browserHeight = window.outerHeight;
if (scrollTop > browserHeight) {
topBtn.style.display = "block";
} else {
topBtn.style.display = "none";
}
},
destroyed() {
window.removeEventListener("scroll", this.scrollToTop);
},
},
};
</script>
<style scoped>
#to-top-btn {
width: 2.4rem;
height: 2.4rem;
position: fixed !important;
top: 30rem;
right: 0.2rem;
display: none;
}
#to-top-btn img {width: 100%;}
</style>