微信小程序并没有提供摇一摇API接口,但是提供了一个重力感应的API 「wx.onAccelerometerChange(CALLBACK)」,我们可以用这个方法来模拟微信摇一摇功能,代码如下:

Page({    onShow: function () {        wx.onAccelerometerChange(function (e) {            console.log(e.x)            console.log(e.y)            console.log(e.z)            if (e.x 1 && e.y 1) {                wx.showToast({                    title: '摇一摇成功',                    icon: 'success',                    duration: 2000                })            }        })    },    onHide: function(){            }})

但如果小程序需要启用tabbar的话,这样启用重力感应API会使tabbar下面所有页面都会监听到重力感应数据,导致模拟摇一摇在所有页面都能出现摇一摇的结果,这并不是我们想要的,我们只是想在tabbar下其中一个页面允许他获取到重力感应数据,那么就需要我们自己加入一个是否在当前页面的判断,根据判断结果来启用监听重力感应API,代码修改如下:

Page({    isShow: false,    onShow: function () {        var that = this;        this.isShow = true;        wx.onAccelerometerChange(function (e) {            if(!that.isShow){                return            }            console.log(e.x)            console.log(e.y)            console.log(e.z)            if (e.x 1 && e.y 1) {                wx.showToast({                    title: '摇一摇成功',                    icon: 'success',                    duration: 2000                })            }        })    },    onHide: function(){        this.isShow = false;    }})

 

TAG标签: 微信小程序微信摇一摇抽奖

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