您的位置:首页 > 移动开发 > 微信开发

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

2018-01-05 17:49 316 查看
需要做个浮在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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息