需求
最近要做一个悬浮可拖动的按钮。按钮跟着手指一起移动,松开按钮时,若按钮此时位于页面中间偏左,按钮就按原高度向左靠。同理,偏右则向右靠。
效果
实现步骤
1.首先我们得有个父的按钮
<!-- 悬浮可拖动按钮 -->
<view class="suspend-btn" style="top:{{btnTop}}px;left:{{btnLeft}}px;"></view>
/* 悬浮按钮样式 */
.suspend-btn {
position: absolute;
z-index: 99;
width: 80rpx;
height: 80rpx;
border-radius: 50%;
background-color: red;
}
2.悬浮之后,我们得有拖动事件3件套
catchtouchmove、catchtouchstart、 catchtouchend
ps:如果你的悬浮按钮除了能拖动还要能点击的话,我们就需要将catchtouchstart 改用成 bindtouchstart
<view class="suspend-btn"
style="top:{{btnTop}}px;left:{{btnLeft}}px;"
bindtransitionend='animationend'
catchtouchmove="buttonMove"
bindtouchstart="buttonStart"
catchtouchend="buttonEnd"
catchtap="clickEvent">
</view>
// 悬浮按钮拖动事件
buttonStart: function (e) {
this.setData({
startSite: e.touches[e.touches.length - 1],
})
},
buttonMove: function (e) {
var endPoint = e.touches[e.touches.length - 1]
var translateX = endPoint.clientX - this.data.startSite.clientX
var translateY = endPoint.clientY - this.data.startSite.clientY
this.data.startSite = endPoint
var btnTop = this.data.btnTop + translateY
var btnLeft = this.data.btnLeft + translateX
//判断是移动否超出屏幕
if (btnLeft + 40 >= this.data.systemInfo.screenWidth) {
btnLeft = this.data.systemInfo.screenWidth - 40;
}
if (btnLeft <= 0) {
btnLeft = 0;
}
if (btnTop <= 40) {
btnTop = 40
}
if (btnTop + 130 >= this.data.systemInfo.screenHeight) {
btnTop = this.data.systemInfo.screenHeight - 130;
}
this.setData({
btnTop: btnTop,
btnLeft: btnLeft,
startSite: e.touches[e.touches.length - 1],
})
},
buttonEnd(e) {
let l = this.data.btnLeft;
if (this.data.btnLeft > this.data.systemInfo.screenWidth / 2 - 30) {
l = this.data.systemInfo.screenWidth - 40
} else {
l = 0;
}
this.setData({
btnLeft: l,
})
},
3.亲妈的提示
若果需要添加动画效果,那么就需要在 buttonMove 和 buttonEnd 这两个时间里面创建wx动画(wx.createAnimation)