继 微信小程序客服浮窗+可移动又有了个小小的需求:浮窗按钮停止触摸后吸附回到左侧。
惯例,先问百度AI:
微信小程序的悬浮按钮做吸附于屏幕边的效果
好吧,别惯例了,这给的答案与我想要的效果相差甚远,现在的问题是movable-view在官方文档中没有获取其监听触摸结束的事件,ok,遇事不决问度娘:微信小程序movable-view怎么知道滑动结束,好嘛,答案也是如此的朴素无华:使用bind:touchend绑定事件即可。
那此时没办法知道移动元素的位置,ok,继续百度:微信小程序movable-view怎么获取移动后的数据,得到大佬的思路。
查找相关的官方API,ok,上代码:
wxml:
<movable-area style="pointer-events: none;height: 100%;width: 100%;position:absolute;left:0px;top:0px;">
<movable-view id="movableView" x="{{mx}}" y="{{my}}" direction="all" bind:touchend="regain" style="pointer-events: auto;height: 18vmin; width: 12vmin; background:#ffffff00;">
<button open-type="contact" bindcontact="handleContact" style="width: 12vmin;height: 18vmin;background-color: #ffffff00;border-radius: 0;z-index: 999999;position: absolute;">
<image src="{{kefu}}" style="width: 15vmin;height: auto;position: relative;margin-top: -4vmin;margin-left: -7vmin;border-radius: 50%;" mode="widthFix"></image>
</button>
</movable-view>
</movable-area>
js:
regain() {
const query = wx.createSelectorQuery()
let that = this;
//movableView是movable-view的Id
query.select('#movableView').boundingClientRect(function (res) {
that.data.movey = res.top
})
query.exec()
setTimeout(function () {
that.setData({
mx: 0, //x轴数值归零,则回左侧
my: that.data.movey //y轴数值不变
})
}, 50)
}
这样咱们就可以将元素触摸后较快的将元素移动回左侧啦