时间:2021-07-01 10:21:17 帮助过:30人阅读
微信小程序并没有提供摇一摇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;
- }
- })
修改以后重新编译预览就达到我们想要的效果了。
总结
以上所述是小编给大家介绍的微信小程序“摇一摇”的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!