组件属性
属性名 | 类型 | 属性值 | 描述 | 默认值 |
---|---|---|---|---|
target | String | “.className” | “#IDName” | 置顶目标 | body |
visibilityHeight | Number | 滚动多少高度显示 | 200 | |
right | Number | 距离浏览器右边距离 | 50 | |
bottom | Number | 距离浏览器下边距离 | 100 |
事件名 | 描述 | 返回值 |
---|---|---|
click | 点击时触发 | event,target(触发目标) |
backtop | 到达目标时触发 | event,target(触发目标) |
代码如下:
<template>
<div
v-show="isShowBackTop"
class="vp-backtop"
@click="backtopHandle"
:style="{ right: `${right}px`, bottom: `${bottom}px` }"
>
<slot>Up</slot>
</div>
</template>
<script>
export default {
name: "VpBacktop",
props: {
target: [String],
visibilityHeight: {
type: Number,
default: 200,
},
right: {
type: Number,
default: 50,
},
bottom: {
type: Number,
default: 100,
},
},
data() {
return {
controllNum: 10,
intervalDelay: 1,
timer: null,
isShowBackTop: false,
};
},
created() {},
mounted() {
window.addEventListener("scroll", this.debounce(this.scrollHandle, 100));
},
methods: {
// 防抖
debounce(fn, wait) {
let timer = null;
return function () {
if (timer !== null) clearInterval(timer);
timer = setTimeout(fn, wait);
};
},
// 点击置顶事件
backtopHandle(e) {
this.$emit("click", e, this.target);
clearInterval(this.timer);
let scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
let target;
if (!this.target) {
target = document.documentElement || document.body;
} else {
if (/^\./.test(this.target)) {
target = document.getElementsByClassName(this.target.substring(1))[0];
} else if (/^#/.test(this.target)) {
target = document.getElementById(this.target.substring(1));
}
}
let _this = this;
if (target.offsetTop < document.documentElement.scrollTop) {
this.timer = window.setInterval(() => {
document.documentElement.scrollTop -= this.controllNum;
if (document.documentElement.scrollTop <= target.offsetTop) {
_this.$emit("backtop", e, _this.target);
window.clearInterval(_this.timer);
}
}, _this.intervalDelay);
} else {
this.timer = window.setInterval(() => {
document.documentElement.scrollTop += this.controllNum;
if (document.documentElement.scrollTop >= target.offsetTop) {
_this.$emit("backtop", e, _this.target);
window.clearInterval(_this.timer);
}
}, _this.intervalDelay);
}
},
// 滚动事件
scrollHandle() {
let scrolltop = document.documentElement.scrollTop;
if (scrolltop >= this.visibilityHeight) {
this.isShowBackTop = true;
} else {
this.isShowBackTop = false;
}
},
},
};
</script>
<style scoped>
.vp-backtop {
cursor: pointer;
position: fixed;
z-index: 999;
padding: 10px 10px;
border: 1px solid cadetblue;
border-radius: 50%;
background-color: cadetblue;
color: aliceblue;
}
</style>
如需要其他更多组件,请移步到本人开发的 Vue 组件库文档:Vpro_UI
如果觉得好的话,请在 Github 上点个 star ,非常感谢!