wxml文件:
<view class="weui-uploader">
<view class="img-v weui-uploader__bd">
<view class='pic' wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
<image class='weui-uploader__img '
src="{{item}}"
data-index="{{index}}" mode="aspectFill" bindtap="previewImg">
<icon type='cancel' class="delete-btn" data-index="{{index}}" catchtap="deleteImg"></icon>
</image>
</view>
<view class="weui-uploader__input-box pic" bindtap="chooseImg"> </view>
</view>
<button class="upload-img-btn" bindtap="chooseImg" type='primary'>拍照 / 上传</button>
</view>
wxss文件:
page{
width: 100%;
padding: 20rpx 20rpx;
}
.weui-uploader__img{
position: relative;
}
.delete-btn{
position: absolute;
top: 5rpx;
right: 5rpx;
}
.upload-img-btn{
margin-top: 5vw
}
js文件:
Page({
/**
* 页面的初始数据
*/
data: {
imgs: []
},
// 上传图片
chooseImg: function (e) {
var that = this;
var imgs = this.data.imgs;
if (imgs.length >= 9) {
this.setData({
lenMore: 1
});
setTimeout(function () {
that.setData({
lenMore: 0
});
}, 2500);
return false;
}
wx.chooseImage({
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
var imgs = that.data.imgs;
for (var i = 0; i < tempFilePaths.length; i++) {
if (imgs.length >= 9) {
that.setData({
imgs: imgs
});
return false;
} else {
imgs.push(tempFilePaths[i]);
}
}
that.setData({
imgs: imgs
});
}
});
},
// 删除图片
deleteImg: function (e) {
var imgs = this.data.imgs;
var index = e.currentTarget.dataset.index;
imgs.splice(index, 1);
this.setData({
imgs: imgs
});
},
// 预览图片
previewImg: function (e) {
//获取当前图片的下标
var index = e.currentTarget.dataset.index;
//所有图片
var imgs = this.data.imgs;
wx.previewImage({
//当前显示图片
current: imgs[index],
//所有图片
urls: imgs
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})