功能描述
1.拍摄或从手机相册中选择图片上传。
2.chooseImage(e) 中的index用于判断是新增图片还是替换图片。
3.delImage(e) 删除当前index索引下的数据。
wx.chooseMedia(Object object)
|
object.success 回调函数
属性 | 类型 | 说明 | |||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tempFiles | Array.<Object> | 本地临时文件列表 | |||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||
type | string | 文件类型,有效值有 image 、video、mix |
wxml部分
<view class="imageList">
<view class="imageItem" wx:for="{{imageList}}" wx:key="index">
<image class="image" mode="aspectFill" bindtap="chooseImage" data-type="pictures" data-index="{{index}}" src="{{item.url}}" alt="" />
<view class="delImage" catchtap="delImage" data-idnex="{{index}}">-</view>
</view>
<view class="imageItem addImage" bindtap="chooseImage" data-type="pictures"></view>
</view>
wxss部分
.imageList {
padding: 32rpx;
width: 100vw;
box-sizing: border-box;
/* 弹性布局 */
display: flex;
flex-direction: row;
justify-content: flex-start;
/* 换行 */
flex-wrap: wrap;
/* 内容区的实际宽度为
width: calc(100vw - 64rpx);
width: 686rpx;
*/
}
/* 照片容器的样式 */
.imageList .imageItem {
margin-bottom: 25rpx;
width: 212rpx;
height: 212rpx;
background: #F7F9FD;
border-radius: 8rpx;
border: 5rpx dotted #D0D0D0;
position: relative;
/* overflow: hidden; */
box-sizing: border-box;
}
.imageList .imageItem:nth-child(3n-1) {
margin: 0 25rpx;
}
/* 图片的样式 */
.imageList .imageItem .image {
display: block;
width: 100%;
height: 100%;
}
/* 删除按钮的样式 */
.imageList .imageItem .delImage {
width: 32rpx;
height: 32rpx;
border-radius: 50%;
background-color: #e40606;
color: #ffffff;
font-size: 32rpx;
text-align: center;
line-height: 22rpx;
position: absolute;
top: -16rpx;
right: -16rpx;
box-sizing: border-box;
}
/* 可以使用背景图 */
.imageList .addImage::before {
display: block;
content: "+";
width: 100rpx;
height: 100rpx;
color: #cccccc;
/* font-weight: 700; */
font-size: 70rpx;
text-align: center;
line-height: 100rpx;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
js部分
Page({
data: {
imageList: []
},
//选择图片
chooseImage(e) {
let index=e.currentTarget.dataset.index
console.log(index)
let self = this
wx.chooseMedia({
count: 9,
sizeType: ['original', 'compressed'], //原图 ,压缩图
sourceType: ['album', 'camera'], //从相处选择 ,使用相机
success(res) {
console.log("res___________",res)
res.tempFiles.forEach((file) => {
if(index === undefined){ //添加图片
self.setData({
imageList: [...self.data.imageList, {
url: file.tempFilePath
}]
})
}else{ //替换当前索引下的图片
self.data.imageList[index].url=file.tempFilePath
self.setData({
imageList:self.data.imageList
})
}
})
}
})
},
//删除图片
delImage(e) {
let {
imageList
} = this.data
let index = e.currentTarget.dataset.index
imageList.splice(index, 1)
this.setData({
imageList
})
}
})