uniapp写一个可拖动全屏,停止左右吸附的按钮

小程序首页浮动按钮,需要可拖动到屏幕任意位置,停止则吸附到左右两边,不遮挡内容

使用到uniapp 的 movable-area

地址:https://uniapp.dcloud.net.cn/component/movable-area.html#movable-area

代码样式

bash 复制代码
<template>
	<view>
		<!-- 发布 -->
		<movable-area class="movable-area">
			 <movable-view 
				class="movable-view" 
				:x="movableX" 
				:y="movableY" 
				direction="all"
				@change="onChange"
				@touchend="onTouchend"
			  >
				<view class="add-box" @click="onAddSource" :style="'margin-left:' +marginHid+'px;'">
					<image class="img" src="/static/image/icon-add-source.png" mode="widthFix"></image>
				</view>
			  </movable-view>
		</movable-area>
	</view>
</template>
bash 复制代码
<script lang="ts">
	export default {
		name:"movable-box",
		props: {
			isScroll: {
				default: false,
				type: Boolean
			}
		},
		data() {
			return {
				movableX: 0,
				movableY: 500,
				screenWidth: 0,
				screenHeight: 0,
				marginHid: 0,
			};
		},
		created() {
			uni.getSystemInfo({
				success: (res) => {
				  this.screenWidth = res.windowWidth
				  this.screenHeight = res.windowHeight
				  // 初始位置在右下角
				  this.movableX = 0
				  this.movableY = 500
				}
			})
		},
		mounted() {
			
		  
		},
		methods: {
			onChange(e: { detail: { x: number; y: number } }) {
				// 拖动时更新坐标
				const threshold = this.screenWidth/ 2 // 吸附阈值
				if (e.detail.x < threshold) this.movableX = 0
				else if (e.detail.x >= threshold) this.movableX = this.screenWidth
				this.movableY = e.detail.y
			},
			onTouchend() {
				const threshold = 50 // 吸附阈值
				if (this.movableX < threshold) this.movableX = 0
				else if (this.movableX >= threshold) this.movableX = this.screenWidth
				if (this.movableY < threshold) this.movableY = 0
				else if (this.movableY > this.screenHeight - threshold) this.movableY = this.screenHeight
			},
			// 去发布
			onAddSource() {
				uni.navigateTo({
						url: '/pages/sourcePackage/resource-save/index'
					})
				
			},
		},
		watch: {
			isScroll() {
				if (this.isScroll) {
					if (this.movableX == 0) {
						this.marginHid = -35
					} else {
						this.marginHid = this.movableX+35
					}
				} else {
					if (this.movableX == 0) {
						this.marginHid = 0
					} else {
						this.marginHid = this.movableX
					}
				}
			}
		}
	}
</script>
bash 复制代码
<style lang="scss">
.movable-area {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none; /* 允许穿透点击 */
  z-index: 9999;
}
.movable-view {
	width: 140rpx;
	height: 140rpx;
	pointer-events: auto; /* 恢复按钮点击 */
}
.add-box {
	width: 140rpx;
	height: 140rpx;
	&.margin-l {
		margin-left: -70rpx;
	}
	&.margin-r {
		margin-right: -70rpx;
	}
	.img {
		width: 100%;
		height: 100%;
		animation: expandContract 1.5s ease-in-out infinite;
	}
	
}

@keyframes expandContract {
  0% { transform: scale(0.8); }
  50% { transform: scale(1); }
  100% { transform: scale(0.8); }
}
</style>

开发遇到的小功能,记录一下。