uniapp小程序客服拖拽+左右吸附

发布时间 2023-07-19 09:04:12作者: 窦戈
<template>
	<view class="" v-if="x != 0 && y != 0">
		<movable-area class="movableArea">
			<movable-view class="movableView" :position="position" :x="x" :y="y" :direction="direction" :damping="damping"
			 @change="onChange" @touchend="onTouchend">
				<image src="../../../../static/images/kefu.png" mode="widthFix" class="iconImage"></image>
				<button open-type='contact' session-from='' class="contact">联系我们</button>
			</movable-view>
		</movable-area>
	</view>
</template>

<script>
	export default {
			data() {
				return {
					x: 0,
					y: 0,
					x1: 0,
					x2: 0,
					y1: 0,
					y2: 0,
					move: {
						x: 0,
						y: 0
					}
				};
			},
			props: {
				damping: {
					type: Number,
					default: 10
				},
				direction: {
					type: String,
					default: "all"
				},
				position: {
					type: Number,
					default: 4
				}
			},
			mounted() {
				uni.getSystemInfo({
					success: (res) => {
						this.x = res.safeArea.right-60;
						this.y = res.safeArea.bottom-280;
						this.x1 = 10;
						this.x2 = parseInt(res.windowWidth) - 60;
					}
				})
			},
			methods: {
				onChange(e) {
					if (e.detail.source === "touch") {
						this.move.x = e.detail.x;
						this.move.y = e.detail.y;
					}
				},
				onTouchend() {
					this.x = this.move.x;
					this.y = this.move.y;
					setTimeout(() => {
						if (this.move.x < this.x2 / 2){
							this.x = this.x1;
						}else{
							this.x = this.x2;
							console.log(this.x, this.y)
						}
					}, 100)
				},
			}
		}
</script>

<style>
	.movableArea {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		pointer-events: none; //设置area元素不可点击,则事件便会下移至页面下层元素
		z-index: 999;
	}
	.movableArea .movableView {
		pointer-events: auto; //可以点击
		width: 80rpx;
		height: 80rpx;
		padding: 8rpx;
		border-radius: 100%;
		border: 1px solid #4BE0C7;
	}
	.movableArea .movableView .iconImage {
		display: block;
		width: 80rpx;
		height: 80rpx;
		// animation: iconImage 5s linear infinite;
	}
	@keyframes iconImage{
	  0%{-webkit-transform:rotate(0deg);}
	  25%{-webkit-transform:rotate(90deg);}
	  50%{-webkit-transform:rotate(180deg);}
	  75%{-webkit-transform:rotate(270deg);}
	  100%{-webkit-transform:rotate(360deg);}
	}
	
	// 客服
	.movableArea .movableView .contact {
		width: 50px;
		height: 50px;
		overflow: hidden;
		position: absolute;
		left: 0px;
		top: 0px;
		border-radius: 100%;
		opacity: 0;
	}
</style>

参考文章:https://www.aliyue.net/10333.html