1、废话不多说,先看效果
2、实现原理
- 运用微信小程序 catchtouchmove 和 bindtouchstart、bindtouchend
- 实时获取按钮再页面当中的位置,进而使用top和left,position等定位属性来实现
3、具体实现代码
HTML【wxml】
<view class="fix_button" bindtap="btnActHandle" catchtouchmove="buttonMove" bindtouchstart="buttonStart" bindtouchend="buttonEnd" style="top:{{buttonTop}}px;left:{{buttonLeft}}px;">
<image class="icon" src="https://z3.ax1x.com/2021/01/17/ssxiKx.png"></image>
</view>
<!-- 这里需要注意的是 -->
<!-- buttonStart和buttonEnd一定不能用catch事件,否则按钮点击事件会失效 -->
CSS【wxss】
.fix_button {
width: 147rpx;
height: 147rpx;
position: fixed;
z-index: 10;
}
.icon {
width: 100%;
height: 100%;
border-radius: 50%;
}
JS
var startPoint;
Page({
data: {
//按钮所在位置坐标
buttonTop: 0,
buttonLeft: 0,
windowHeight: '',
windowWidth: '',
},
btnActHandle() {
},
onLoad: function () {
wx.getSystemInfo({
success: (res) => {
this.setData({
windowHeight: res.windowHeight,
windowWidth: res.windowWidth,
buttonTop: res.windowHeight * 0.60, //设置按钮的初始位置
buttonLeft: res.windowWidth * 0.80,
})
}
})
},
//按钮拖动事件
buttonStart: function (e) {
startPoint = e.touches[0] //获取拖动开始点
},
buttonMove: function (e) {
//获取拖动结束点
var endPoint = e.touches[e.touches.length - 1]
//计算在X轴上拖动的距离和在Y轴上拖动的距离
var translateX = endPoint.clientX - startPoint.clientX
var translateY = endPoint.clientY - startPoint.clientY
//重置开始位置
startPoint = endPoint
var buttonTop = this.data.buttonTop + translateY
var buttonLeft = this.data.buttonLeft + translateX
//判断是移动否超出屏幕
if (buttonLeft + 50 >= this.data.windowWidth) {
buttonLeft = this.data.windowWidth - 50;
}
if (buttonLeft <= 0) {
buttonLeft = 0;
}
if (buttonTop <= 0) {
buttonTop = 0
}
if (buttonTop + 50 >= this.data.windowHeight) {
buttonTop = this.data.windowHeight - 50;
}
this.setData({
buttonTop: buttonTop,
buttonLeft: buttonLeft
})
},
buttonEnd: function (e) {}
})
4、实现简单,代码片段复制粘贴,即可预览效果体验效果。最后,贴一下自己的小程序,喜欢可以扫码查看