這里均用的是小程序原生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鏈接列表
})
},
})