其他分享
首页 > 其他分享> > 【uniapp】使用wxs实现多个可自由拖动的元素

【uniapp】使用wxs实现多个可自由拖动的元素

作者:互联网

wxs语法参考

wxs语法参考

代码

<template>  
	<view class="area">  <!-- 注意:每个页面只能有一个根view -->
		<view>
			<view @touchstart="test1.touchstart" @touchmove="test1.touchmove" class="movable">{{test1.msg1}}</view>
		</view>
		
		<view>
			<view @touchstart="test2.touchstart" @touchmove="test2.touchmove" class="movable2">{{test2.msg2}}</view>
		</view>
	</view>

</template>
<script module="test1" lang="wxs">   //第一个元素的wxs模块
	var startX = 0
	var startY = 0
	var lastLeft = 50; var lastTop = 50
	
	function touchstart(event, ins) {   // 获取手指点按的元素的初始位置
		var touch = event.touches[0] || event.changedTouches[0]
		startX = touch.pageX
		startY = touch.pageY
	}  
	function touchmove(event, ins) {    // 获取元素被拖动后的位置
		var touch = event.touches[0] || event.changedTouches[0]
		var pageX = touch.pageX
		var pageY = touch.pageY
		var left = pageX - startX + lastLeft
		var top = pageY - startY + lastTop
		startX = pageX
		startY = pageY
		lastLeft = left
		lastTop = top
		ins.selectComponent('.movable').setStyle({  // 更新符合条件——“class=.movable” 的元素中left和top的值
			left: left + 'px',
			top: top + 'px'
		})
	}
	module.exports = {
		msg1: 'Hello1',
		touchstart: touchstart,
		touchmove: touchmove
	}
</script>


<script module="test2" lang="wxs">   //第二个元素的wxs模块
	var startX = 100
	var startY = 100
	var lastLeft = 150; var lastTop = 150
	function touchstart(event, ins) {
		var touch = event.touches[0] || event.changedTouches[0]
		startX = touch.pageX
		startY = touch.pageY
	}
	function touchmove(event, ins) {
		var touch = event.touches[0] || event.changedTouches[0]
		var pageX = touch.pageX
		var pageY = touch.pageY
		var left = pageX - startX + lastLeft
		var top = pageY - startY + lastTop
		startX = pageX
		startY = pageY
		lastLeft = left
		lastTop = top
		ins.selectComponent('.movable2').setStyle({
			left: left + 'px',
			top: top + 'px'
		})
	}
	module.exports = {
		msg2: 'Hello2',
		touchstart: touchstart,
		touchmove: touchmove
	}
</script>

<script>
	export default {
		data() {
			return {
			}
		},
		methods: {
		}
	}
</script>

<style>
	.area{    
		position: absolute;
		width: 100%;
		height: 100%;
	}
	.movable{
		position: absolute;
		width: 100px;
		height: 100px;
		left: 50px;
		top: 50px;
		color: white;
		text-align: center;
		line-height: 100px;
		background-color: red;
	}
	.movable2{
		position: absolute;
		width: 100px;
		height: 100px;
		left: 150px;
		top: 150px;
		color: white;
		text-align: center;
		line-height: 100px;
		background-color: red;
	}
</style>

效果

image

标签:uniapp,wxs,拖动,top,touch,pageX,var,event,left
来源: https://www.cnblogs.com/oasismove/p/16243017.html