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

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

上GIF:



Android中也会有类似移动控件的操作.思路差不多.获取到位移的X Y 的变量,给控件设置坐标.


1.index.wxml

[html]  view plain  copy
  1. <image class="image-style" src="../../images/gundong.png" bindtap="ballClickEvent" style="bottom:{{ballBottom}}px;right:{{ballRight}}px;" bindtouchmove="ballMoveEvent">   
  2. </image>  

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


2.index.js

[javascript]  view plain  copy
  1. //index.js  
  2. //获取应用实例  
  3. var app = getApp()  
  4. Page({  
  5.   data: {  
  6.     ballBottom: 240,  
  7.     ballRight: 120,  
  8.     screenHeight: 0,  
  9.     screenWidth: 0,  
  10.   },  
  11.   onLoad: function () {  
[javascript]  view plain  copy
  1. <span style="white-space:pre">  </span>//获取屏幕宽高  
  2.     var _this = this;  
  3.     wx.getSystemInfo({  
  4.       success: function (res) {  
  5.         _this.setData({  
  6.           screenHeight: res.windowHeight,  
  7.           screenWidth: res.windowWidth,  
  8.         });  
  9.       }  
  10.     });  
  11.   },  
  12.   ballMoveEvent: function (e) {  
  13.     console.log('我被拖动了....')  
  14.     var touchs = e.touches[0];  
  15.     var pageX = touchs.pageX;  
  16.     var pageY = touchs.pageY;  
  17.     console.log('pageX: ' + pageX)  
  18.     console.log('pageY: ' + pageY)  
[javascript]  view plain  copy
  1. //防止坐标越界,view宽高的一般  
  2.     if (pageX < 30) return;  
  3.     if (pageX > this.data.screenWidth - 30) return;  
  4.     if (this.data.screenHeight - pageY <= 30) return;  
  5.     if (pageY <= 30) return;  
[javascript]  view plain  copy
  1. //这里用right和bottom.所以需要将pageX pageY转换  
  2.     var x = this.data.screenWidth - pageX - 30;  
  3.     var y = this.data.screenHeight - pageY - 30;  
  4.     console.log('x: ' + x)  
  5.     console.log('y: ' + y)  
  6.     this.setData({  
  7.       ballBottom: y,  
  8.       ballRight: x  
  9.     });  
  10.   },  
[javascript]  view plain  copy
  1. //点击事件  
  2.   ballClickEvent: function () {  
  3.     console.log('点击了....')  
  4.   }  
  5. })  


3.index.wxss

这里需要设置z-index

[css]  view plain  copy
  1. .image-style{  
  2.   positionabsolute;  
  3.   bottom: 240px;  
  4.   right: 100px;  
  5.   width60px;  
  6.   height60px;  
  7.   z-index100;  
  8. }  

http://blog.csdn.net/qq_31383345

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值