最近有一个需求把icon 实现可以滑动,然后带边缘吸附效果,话不多说,上代码吧。
image.png
xml
<image
catchtap="newGift"
class="toShop-btn"
style="left:{{left}}px;top:{{top}}px;"
bindtouchmove="viewTouchMove"
bindtouchend="viewTouchend"
wx:if="{{isAuto==true || offflng==0}}"
src='https://tmawx.shenzhenair.com/Shwxcharfile/ts/app/newmoney.png'></image>
css
.toShop-btn{
position: fixed;
top:481rpx;
width: 60px;
height:65px;
line-height: 48px;
z-index:9999;
right:0rpx;
-moz-animation: myfirst 1s infinite;
-webkit-animation: myfirst 1s infinite;
-o-animation: myfirst 1s infinite;
animation: myfirst 1s infinite;
background:none;
}
@keyframes myfirst{
0% { transform: scale(.8); }
50% { transform: scale(1); }
100% { transform: scale(.8); }
}
js
data:{
left: '',
top: ''
}
viewTouchMove: function (e) {
const widthHalf = app.globalData.width / 2;
console.log(widthHalf)
console.log(e.touches[0].clientX);
this.setData({
left: e.touches[0].clientX - 30,
top: e.touches[0].clientY - 30
})
if (e.touches[0].clientX < 0) {
e.touches[0].clientX = 0;
};
//这里要注意一下条件:位移X > 宽度-图片宽度
if (e.touches[0].clientX > app.globalData.width - 60) {
e.touches[0].clientX = app.globalData.width - 60;
};
if (app.globalData.heighttwo - e.touches[0].clientY - 35 <= 0) {
e.touches[0].clientY = app.globalData.heighttwo -35;
};
if (e.touches[0].clientY < 0) {
e.touches[0].clientY = 0;
};
this.setData({
left: e.touches[0].clientX-10 ,
top: e.touches[0].clientY-30
})
},
//拖拽结束后的事件
viewTouchend(e) {
const widthHalf = app.globalData.width / 2;
if (e.changedTouches[0].clientX > widthHalf) {
console.log("我是右边")
e.changedTouches[0].clientX = app.globalData.width - 60;
}
if (e.changedTouches[0].clientX < widthHalf) {
console.log("我是左边")
e.changedTouches[0].clientX = 0;
}
this.setData({
left: e.changedTouches[0].clientX - 0,
})
},
/* 添加授权判断 */
//star 修改 点击不要赠送
onClose() {
const that = this;
console.log('点击关闭我')
that.setData({
showUserInfo: false
})
},