14.wx.showToast交互反馈
post-detail.js添加个消息提示框
onCollectionTap: function(ev) {
var postsCollected = wx.getStorageSync('posts_Collected')
var postCollected = postsCollected[this.data.currentPostId]
postCollected = !postCollected;
postsCollected[this.data.currentPostId] = postCollected;
// 更新文章是否收藏的缓存值
wx.setStorageSync('posts_Collected', postsCollected)
// 更新数据绑定变量,实现切换图片
this.setData({
collected: postCollected
})
wx.showToast({
title: postCollected ? "收藏成功" : "取消成功",
duration: 1000,
icon: "success"
})
}
效果
15.音乐播放功能
在posts-data.js里面给每篇文章添加一个music属性
music: {
url: "http://music.163.com/song/media/outer/url?id=108242.mp3",
title: "她说-林俊杰",
coverImg: "http://y.gtimg.cn/music/photo_new/T002R150x150M000001TEc6V0kjpVC.jpg?max_age=2592000"
}
post-detail.wxml
- 没播放音乐就显示文章图片,播放音乐就显示音乐歌手图片
- 绑定事件,添加播放和暂停音乐以及图片切换功能
<!-- <image class="head-image" src="{{postData.headImgSrc}}"></image> -->
<image class='head-image' src="{{isPlayingMusic?postData.music.coverImg:postData.headImgSrc}}"></image>
<image catchtap='onMusicTap' class='audio' src="{{isPlayingMusic? '/images/music/music-stop.png': '/images/music/music-start.png'}}"></image>
post-detail.js
// 播放音乐
onMusicTap: function (ev) {
var currentPostId = this.data.currentPostId;
var postData = postsData.postlist[currentPostId];
var isPlayingMusic = this.data.isPlayingMusic;
if (isPlayingMusic) {
wx.pauseBackgroundAudio();
this.setData({
isPlayingMusic: false
})
}
else {
wx.playBackgroundAudio({
dataUrl: postData.music.url,
title: postData.music.title,
coverImgUrl: postData.music.coverImg,
})
this.setData({
isPlayingMusic: true
})
}
}
16.监听音乐播放事件
post-detail.js的onLoad函数里面添加监听事件
var that = this;
wx.onBackgroundAudioPlay(function(){
that.setData({
isPlayingMusic: true
})
});
wx.onBackgroundAudioPause(function () {
that.setData({
isPlayingMusic: false
})
});
},
绑定监听事件后,播放按钮的状态就可以同步切换了
17.完善音乐播放功能
在文章详情页,点击播放音乐后,然后返回到文章列表页,再进到详情页,发现播放按钮是暂停状态,这是因为应用程序存在生命周期,下面就解决这个问题。
app.js绑定一个全局的变量(音乐播放状态)
App({
globalData: {
g_isPlayingMusic: false,
g_currentMusicPostId: null,
},
})
post-detail.js
var app = getApp();
Page({
data: {
isPlayingMusic: false
},
onLoad: function(options) {
.
.
.
if (app.globalData.g_isPlayingMusic && app.globalData.g_currentMusicPostId === postId) {
this.setData({
isPlayingMusic: true
})
}
this.setMusicMonitor()
},
setMusicMonitor:function(){
var that = this;
wx.onBackgroundAudioPlay(function () {
that.setData({
isPlayingMusic: true
})
app.globalData.g_currentMusicPostId = that.data.currentPostId
app.globalData.g_isPlayingMusic = true
});
wx.onBackgroundAudioPause(function () {
that.setData({
isPlayingMusic: false
})
app.globalData.g_currentMusicPostId = null
app.globalData.g_isPlayingMusic = false
});
},
18.轮播图跳转到文章详情
post.wxml
<swiper catchtap='onSwiperTap' indicator-dots='true' autoplay='true' interval='2000'>
post.js
onSwiperTap(event) {
var postId = event.target.dataset.postid
wx.navigateTo({
url: 'post-detail/post-detail?id=' + postId
})
},