vue悬浮球一键式制作

本文详细描述了一个移动端悬浮按钮组件的Vue.js实现,涉及组件样式、尺寸计算、触屏开始、移动和结束时的事件监听,以及与父组件的交互。
摘要由CSDN通过智能技术生成
<!-- 可拖拽的小球 封装 -->
<template>
	<div
		ref="floatButton"
		class="backHome"
		@click="goCreatePage"
		:style="{
			width: itemWidth + 'px',
			height: itemHeight + 'px',
			left: left + 'px',
			top: top + 'px',
		}"
	>
		<img src="../../assets/images/GoBook.png" />
	</div>
</template>
 
<script>
export default {
	name: 'BackHome',
	props: {
		itemWidth: {
			// 悬浮按钮宽度
			type: Number,
			default: 64,
		},
		itemHeight: {
			// 悬浮按钮高度
			type: Number,
			default: 64,
		},
		gapWidth: {
			// 距离左右两边距离
			type: Number,
			default: 10,
		},
		coefficientHeight: {
			// 从上到下距离比例
			type: Number,
			default: 0.72,
		},
	},
	data() {
		return {
			top: 0,
			left: 0,
			currentTop: 0,
			clientWidth: 0,
			clientHeight: 0,
			timer: null,
		};
	},
	created() {
		this.clientWidth = document.documentElement.clientWidth; // 手机宽度
		this.clientHeight = document.documentElement.clientHeight;
		this.left = this.clientWidth - this.itemWidth - this.gapWidth;
		this.top = this.clientHeight * this.coefficientHeight;
	},
	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 =
						this.clientWidth - this.itemWidth - this.gapWidth;
					// this.left = document.documentElement.clientWidth - 60;
				} else {
					this.left = 10;
					// this.left = 0;
				}
			});
		});
	},
	methods: {
		// 返回首页菜单
		goCreatePage() {
			this.$emit('goManage');
		},
	},
};
</script>
 
<style lang="scss" scoped>
.backHome {
	position: fixed;
	z-index: 999;
	img {
		width: 100%;
		height: 100%;
	}

}
</style>

父组件使用

    <levitatedSphere  @goManage="goManage"></levitatedSphere>

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值