Home  >  Article  >  WeChat Applet  >  Introduction to the method of implementing the shake function in WeChat mini program

Introduction to the method of implementing the shake function in WeChat mini program

黄舟
黄舟Original
2017-09-13 09:50:444513browse

The WeChat applet does not provide a shake API interface, but it provides a gravity sensing API. Next, we can use this method to simulate the WeChat shake function. For the specific implementation code, please refer to this article

The WeChat applet does not provide a shake API interface, but it provides a gravity sensing API "wx.onAccelerometerChange(CALLBACK)". We can use this method to simulate the WeChat shake function. The code is as follows:


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(){
  }
})

But if the mini program needs to enable the tabbar, enabling the gravity sensing API will cause all pages under the tabbar to monitor the gravity sensing data, causing the simulated shake to appear on all pages. The result of shaking is not what we want. We just want to allow one of the pages under the tabbar to obtain the gravity sensing data. Then we need to add a judgment of whether it is on the current page, and based on the judgment result To enable monitoring of the gravity sensing API, the code is modified as follows:


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;
  }
})

After modification, recompile the preview to achieve the effect we want.

Summarize

The above is the detailed content of Introduction to the method of implementing the shake function in WeChat mini program. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn