需求:  微信小程序中,一张小图标,可以在窗口中来回拖动。

解决方法:

使用小程序的movable-area组件,

movable-area class="movableArea"movable-view class="movableView" style="height: 50rpx; width: 50rpx; background:                                       blue;" x="{{x}}" y="{{y}}" direction="all" bindtouchend="moveEnd"    view class="movableBtn"    图标    /view    /movable-view/movable-area

样式:

主要利用css3的pointer-events属性,给movable-area设置上pointer-events: none;那么该元素不在是鼠标事件的目标,鼠标不再监听当前层而去监听下面的层中的元素。给他的子级movable-view设置上pointer-events: auto,那么子元素还是鼠标事件的目标。

.movableArea {position: fixed;width: 100%;height: 100%;pointer-events: none;}.movableView {pointer-events: auto;}.movableBtn {width: 100%;height: 100%;font-size: 26rpx;}

js:

实现图标定位到左侧20px或者右侧20px。

data: {    x: 0,    y: 0},moveEnd (e) {//想让他定位到,距离左侧20px(750的图片),通过计算,来适应不同的手机屏幕  var xNumLeft = 20 / 750 * wx.getSystemInfoSync().windowWidth;//想让他定位到,距离右侧20px(750的图片),自身宽度为50在加上20,计算出x为680  var xNumRight = 680 / 750 * wx.getSystemInfoSync().windowWidth;  var x = e.changedTouches[0].pageX;  var average = 375 / 750 * wx.getSystemInfoSync().windowWidth;//获取移动到的y轴,手指松开后,直接上图标定位到当前y轴  var yNum = e.changedTouches[0].pageY;  console.log(yNum)  if (x average) {  this.setData({  x: xNumLeft,y: yNum  })  } else {  this.setData({  x: xNumRight,y: yNum  })  }}

 

TAG标签: 微信小程序movable

http://www.xiaochengxub.com/read-104389.html