微信小程序开发之拖拽 image 触摸事件监听

需要做个浮在scroll-view之上的button.尝试了一下.

上GIF:


1.index.wxml

简单的设置一张图片,添加触摸事件监听.点击事件监听.根据触摸事件获取X Y位移,设置为image的位置

< image class= "image-style" src= "../../images/sand.png" bindtap= "ballClickEvent" style= "bottom:{{ballBottom}}px;right:{{ballRight}}px;" bindtouchmove= "ballMoveEvent">
</ image >

2.index.js

data: {
ballBottom: 80,/**初始位置*/
ballRight: 220, /**初始位置*/
screenHeight: 0,
screenWidth: 0,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this;
wx.getSystemInfo({
success: function (res) {
_this.setData({
screenHeight: res.windowHeight,
screenWidth: res.windowWidth,
});
}
});
},

//开始移动事件
ballMoveEvent: function (e) {
console.log( '我被拖动了....')
var touchs = e.touches[ 0];
var pageX = touchs.pageX;
var pageY = touchs.pageY;
console.log( 'pageX: ' + pageX)
console.log( 'pageY: ' + pageY)
//防止坐标越界,view宽高的一般
if (pageX < 30) return;
if (pageX > this.data.screenWidth - 30) return;
if ( this.data.screenHeight - pageY <= 30) return;
if (pageY <= 30) return;
//这里用right和bottom.所以需要将pageX pageY转换
var x = this.data.screenWidth - pageX - 30;
var y = this.data.screenHeight - pageY - 30;
console.log( 'x: ' + x)
console.log( 'y: ' + y)
this.setData({
ballBottom: y,
ballRight: x
});
},


ballClickEvent: function () {
console.log( '点击了....')
},

3.index.wxss

这里需要设置z-index

.image-style{
position: absolute;
bottom: 240px;
right: 100px;
width: 60px;
height: 60px;
z-index: 100;
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值