这里均用的是小程序原生api
废话不多说直接上栗子:
<view class="addImv">
<!--这个是已经选好的图片-->
<view wx:for="{{banner}}" wx:key="key" class="upFile" bindtap="showImageBanner" style="border-radius: 5px" data-id="{{index}}">
<image class="itemImv" src="{{item}}"></image>
<image class="closeImv" src="../../resources/images/delect.png" mode="scaleToFill" catchtap="deleteImvBanner" data-id="{{index}}"></image>
</view>
<!--这个是选择图片-->
<view class="chooseView" bindtap="chooseBanner" style="border-radius: 5px" wx:if="{{chooseViewShowBanner}}">
<image class="chooseImv" src="../../resources/images/add.png"></image>
</view>
</view>
/*选择图片View*/
.addImv {
background-color: white;
/* border: 1px dashed gray; */
display: flex;
flex-wrap: wrap;
align-items: center;
margin-top: 5rpx;
}
.upImv {
background-color: white;
width: 100%;
margin-top: 5rpx;
}
.upImv_text {
font-size: 30rpx;
margin-left: 20rpx;
padding-top: 20rpx;
}
/*添加图片*/
.addImv .chooseView {
width: 180rpx;
height: 180rpx;
margin: 20rpx 20rpx;
background-color: #f2f6f9;
border: 1px dashed lightgray;
text-align: center;
line-height: 180rpx;
/* padding: 0rpx 7rpx; */
border-radius: 5px;
margin-left: 40rpx;
}
.addImv .chooseImv {
width: 50rpx;
height: 50rpx;
}
/*已选择的图片*/
.addImv .upFile {
width: 180rpx;
height: 180rpx;
position: relative;
padding: 0rpx 7rpx;
margin-left: 40rpx;
border: 1px solid #c0ccda;
}
.addImv .upFile .itemImv {
width: 180rpx;
height: 180rpx;
padding: 0rpx 7rpx;
}
.addImv .upFile .closeImv {
position: absolute;
right: 0rpx;
top: 0rpx;
width: 50rpx;
height: 50rpx;
}
Page({
/**
* 页面的初始数据
*/
data: {
banner: [], //轮播图片
},
/** 选择图片Banner */
chooseBanner: function() {
var that = this;
if (this.data.banner.length < 2) {
wx.chooseImage({
count: 2, //最多选择2张图片- that.data.banner.length,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
console.log(res.tempFilePaths);
if (res.tempFilePaths.count == 0) {
return;
}
//上传图片
var imgArrNow = that.data.banner;
imgArrNow = imgArrNow.concat(res.tempFilePaths);
that.setData({
banner: imgArrNow
})
that.chooseViewShowBanner();
}
})
} else {
wx.showToast({
title: '限制选择6个文件',
icon: 'loading',
duration: 1000
})
}
},
/** 删除图片Banner */
deleteImvBanner: function(e) {
var banner = this.data.banner;
var itemIndex = e.currentTarget.dataset.id;
banner.splice(itemIndex, 1);
this.setData({
banner: banner
})
//判断是否隐藏选择图片
this.chooseViewShowBanner();
},
/** 是否隐藏图片选择Banner*/
chooseViewShowBanner: function() {
if (this.data.banner.length >= 2) {
this.setData({
chooseViewShowBanner: false
})
} else {
this.setData({
chooseViewShowBanner: true
})
}
},
/** 查看大图Banner */
showImageBanner: function(e) {
var banner = this.data.banner;
var itemIndex = e.currentTarget.dataset.id;
console.log("itemIndex:" + JSON.stringify(e))
wx.previewImage({
current: banner[itemIndex], // 当前显示图片的http链接
urls: banner // 需要预览的图片http链接列表
})
},
})