How to adapt the button of the system in the WeChat applet

In the WeChat applet, we can use the officially provided API to adapt the buttons of the system.

  1. Back button adaptation

If you need to display a back button on the page, and click the button to return to the previous page or multi-level page, you can use wx.navigateBack()the API. The sample code is as follows:

// 在页面 JS 文件中调用 navigateBack() API
onTapBack: function () {
    
    
  wx.navigateBack({
    
    
    delta: 1
  })
}

If the current page is navigated to through the TabBar, then using wx.navigateBack()is invalid, and needs to be used wx.switchTab()to return to the TabBar page.

// 在 TabBar 页面中调用 switchTab() API
onTapBack: function () {
    
    
  wx.switchTab({
    
    
    url: '/pages/index/index'
  })
}
  1. Share button adaptation

If you need to display a share button on the page and click the button to share, you can use wx.showShareMenu()the API to display the system's default share button, and you can wx.onShareAppMessage()define custom share content through the API. The sample code is as follows:

// 在页面 onLoad 函数中调用 showShareMenu() API
onLoad: function () {
    
    
  wx.showShareMenu({
    
    
    withShareTicket: true
  });
},

//定义自定义分享内容的回调函数
onShareAppMessage: function (res) {
    
    
  return {
    
    
    title: '分享标题',
    path: '/pages/index/index',
    imageUrl: '/images/share.png'
  }
}
  1. Forward button adaptation

If you need to display a forward button on the page and click the button to forward the page to other users, you can use the wx.updateShareMenu()API to update the state of the forward button, and wx.onShareAppMessage()define custom forward content through the API. The sample code is as follows:

// 在页面 onLoad 函数中调用 updateShareMenu() API
onLoad: function () {
    
    
  wx.updateShareMenu({
    
    
    withShareTicket: true,
    isUpdatableMessage: false,
    activityId: null,
    templateInfo: null
  });
},

// 定义自定义转发内容的回调函数
onShareAppMessage: function (res) {
    
    
  return {
    
    
    title: '转发标题',
    path: '/pages/index/index',
    imageUrl: '/images/share.png'
  }
}
  1. Button Position Adaptation

If you need to customize the position of the button in the page, you can use CSS style to control the position and style of the button. For example, you can use positionthe property to set the position of the button, background-colorthe property to set the background color of the button, colorthe property to set the font color of the button, and so on. The sample code is as follows:

/* 在页面 CSS 文件中设置按钮样式 */
.button {
    
    
  position: absolute;
  top: 20px;
  left: 20px;
  width: 100px;
  height: 40px;
  background-color: #2f4554;
  color: #fff;
  font-size: 16px;
  border-radius: 4px;
  text-align: center;
  line-height: 40px;
}
<!-- 在页面 WXML 文件中添加按钮 -->
<button class="button">返回</button>

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/131138111