先看成品
可以随意拖拽且不会超出屏幕的盒子
1、先随便写个固定定位到的盒子
注意盒子的距离屏幕左边和上边的距离用个全局变量代替,
方便拖拽的时候修改。
<view class="movebox" style="position: fixed;left: {{buttonLeft}}rpx;top: {{buttonHeight}}rpx;">
<image src="../../aseets/海琴烟.jpg" mode="" class="moveImage"/>
</view>
data: {
buttonLeft:567,
buttonHeight:650
},
2、使用微信小程序api获取设备的宽高(单位是px)
因为单位是px,我们如果做成自适应的,需要将px转换成rpx。
微信小程序屏幕宽度是750rpx
在data中定义数据
windowWidth:'',//设备的屏幕宽度
windowHeight:''//设备的屏幕高度
pixelRatio1:'',//px换算rpx
在onload中获取屏幕宽高()
onLoad(options) {
const that=this
wx.getSystemInfo({
success: function (res) {
console.log(res);
// 屏幕宽度、高度
console.log('height=' + res.windowHeight);
console.log('width=' + res.windowWidth);
// 高度,宽度 单位为px
that.setData({
windowHeight: res.windowHeight,
windowWidth: res.windowWidth,
pixelRatio1:750 / res.windowWidth//px换算成rpx
})
}
})
},
3、监听盒子的起始位置和终止位置
在position:fixed的盒子上加上小程序自带的监听事件
<view class="movebox" style="position: fixed;left: {{buttonLeft}}rpx;top: {{buttonTop}}rpx;" bindtouchmove="buttonMove" bindtouchstart="buttonStart">
<image src="../../aseets/海琴烟.jpg" mode="" class="moveImage"/>
</view>
在最外侧注册一个起始变量
var startPoint;//起始点位置
Page({
/**
* 页面的初始数据
*/
data: {
buttonLeft:567,
buttonTop:650,
windowWidth:'',//设备的屏幕宽度
windowHeight:'',//设备的屏幕高度
pixelRatio1:'',//px换算rpx
},
对盒子的起始位置进行计算
buttonStart: function (e) {
startPoint = e.touches[0]//盒子的起始位置
},
buttonMove: function (e) {
var endPoint = e.touches[e.touches.length - 1]//盒子的结束位置
var translateX = (endPoint.clientX - startPoint.clientX)*this.data.pixelRatio1//x轴移动的距离换算成rpx
var translateY = (endPoint.clientY - startPoint.clientY)*this.data.pixelRatio1//y轴移动的距离换算成rpx
startPoint = endPoint//这次是结束位置是下次的起始位置
var buttonTop = this.data.buttonTop + translateY//起始的位置加上移动的距离就是现在的位置
var buttonLeft = this.data.buttonLeft + translateX//起始的位置加上移动的距离就是现在的位置
// console.log(buttonLeft,this.data.windowWidth*this.data.pixelRatio1);
//判断是移动否超出屏幕
// 如果左侧和上边超出屏幕则让其帖住屏幕
if (buttonLeft <= 0) {
buttonLeft = 0;
}
if (buttonTop <= 0) {
buttonTop = 0
}
// 判断右侧和底部是否超出屏幕,如果超出去则回退一个盒子的宽高
if (buttonLeft + 160 >= this.data.windowWidth * this.data.pixelRatio1) {
buttonLeft = this.data.windowWidth * this.data.pixelRatio1 - 160;
}
if (buttonTop + 90 >= this.data.windowHeight * this.data.pixelRatio1) {
buttonTop = this.data.windowHeight * this.data.pixelRatio1- 90;
}
this.setData({
buttonTop: buttonTop,
buttonLeft: buttonLeft
})
},