刚好最近在开发这个效果,直接拿去复制就可以用,之后再遇到这种,可以直接拿代码~ 有需要的可以拿
<!-- 可拖拽的小球 封装 -->
<template>
<div
class="backHome"
ref="floatButton"
@click="goCreatePage"
:style="{
width: itemWidth + 'px',
height: itemHeight + 'px',
left: left + 'px',
top: top + 'px',
}"
>
<img src="" alt="" />
</div>
</template>
<script>
export default {
name: "BackHome",
props: {
itemWidth: {
// 悬浮按钮宽度
type: Number,
default: 40,
},
itemHeight: {
// 悬浮按钮高度
type: Number,
default: 50,
},
gapWidth: {
// 距离左右两边距离
type: Number,
default: 20,
},
coefficientHeight: {
// 从上到下距离比例
type: Number,
default: 0.72,
},
},
data() {
return {
ssicId: "",
clientWidth: 0,
clientHeight: 0,
timer: null,
currentTop: 0,
left: 0,
top: 0,
};
},
created() {
// this.ssicId = sessionStorage.getItem("ssicId");
this.clientWidth = document.documentElement.clientWidth;
this.clientHeight = document.documentElement.clientHeight;
this.left = this.clientWidth - this.itemWidth - this.gapWidth;
this.top = this.clientHeight * this.coefficientHeight;
},
methods: {
// 返回首页菜单
goCreatePage() {
this.$emit("goManage");
// location.href = ``;
},
handleScrollEnd() {
let scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop === this.currentTop) {
if (this.left > this.clientWidth / 2) {
this.left = this.clientWidth - this.itemWidth - this.gapWidth;
} else {
this.left = this.gapWidth;
}
}
clearTimeout(this.timer);
},
},
mounted() {
this.$nextTick(() => {
const floatButton = this.$refs.floatButton;
floatButton.addEventListener("touchstart", () => {
floatButton.style.transition = "none";
});
// 在拖拽过程中,组件应该跟随手指的移动而移动
floatButton.addEventListener("touchmove", (e) => {
if (e.targetTouches.length === 1) {
// 一根手指
let touch = e.targetTouches[0];
this.left = touch.clientX - 20;
this.top = touch.clientY - 25;
}
});
// 拖拽结束后,重新调整组件的位置并重新设置过渡动画
floatButton.addEventListener("touchend", () => {
floatButton.style.transition = "all 0.3s";
if (this.left > document.documentElement.clientWidth / 2) {
this.left = document.documentElement.clientWidth - 60;
} else {
this.left = 0;
}
});
});
},
beforeDestroy() {
window.removeEventListener("scroll", this.handleScrollStart);
},
};
</script>
<style lang="scss" scoped>
.backHome {
position: fixed;
bottom: 165px;
right: 15px;
z-index: 999;
width: 61px;
height: 61px;
img {
width: 61px;
height: 61px;
}
}
</style>