Skip to content

Instantly share code, notes, and snippets.

@ShuJun-Junical
Created May 22, 2021 05:30
Show Gist options
  • Save ShuJun-Junical/db9021be035456b0c8f6c12631f5fc8e to your computer and use it in GitHub Desktop.
Save ShuJun-Junical/db9021be035456b0c8f6c12631f5fc8e to your computer and use it in GitHub Desktop.
Vue 组件:一键回顶按钮
<template>
<v-fab-transition>
<v-btn
v-show="btnFlag"
color="pink"
dark
bottom
right
fab
fixed
@click="backTop"
>
<v-icon>mdi-arrow-up-thick</v-icon>
</v-btn>
</v-fab-transition>
</template>
<script>
export default {
name: 'BackTop',
data() {
return {
btnFlag: false,
};
},
mounted() {
window.addEventListener('scroll', this.scrollToTop);
},
destroyed() {
window.removeEventListener('scroll', this.scrollToTop);
},
methods: {
backTop() {
const that = this;
const timer = setInterval(() => {
const ispeed = Math.floor(-that.scrollTop / 5);
document.documentElement.scrollTop = document.body.scrollTop =
that.scrollTop + ispeed;
if (that.scrollTop === 0) {
clearInterval(timer);
}
}, 16);
},
scrollToTop() {
const that = this;
const scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
that.scrollTop = scrollTop;
if (that.scrollTop > 60) {
that.btnFlag = true;
} else {
that.btnFlag = false;
}
},
},
};
</script>
@ShuJun-Junical
Copy link
Author

Template部分使用Vuetify框架。将本组件加载到Vue根组件上即可。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment