微信小程序实现常用添加图片功能, 预览, 删除(完整版)超详细

编程入门 行业动态 更新时间:2024-10-05 05:20:33

微信小程序实现常用添加图片功能, 预览, 删除(<a href=https://www.elefans.com/category/jswz/34/1770030.html style=完整版)超详细"/>

微信小程序实现常用添加图片功能, 预览, 删除(完整版)超详细

我们先来看看效果图吧

我们来看看代码是怎么实现的

 wxml

<view class="img-li" wx:for="{{imgList}}" wx:key="index"><image class="uploading-icon" src="{{item}}"></image></view>
<view class="img-li" wx:if="{{imgList.length<=5}}" bindtap="chooseSource"><image class="uploading-icon" src="../../../img/icon/icon-uploading-gray.png"></image></view>

wxss

.img-li {width: 23%;height: 170rpx;margin-right: 20rpx;margin-bottom: 20rpx;
}
.img-li:nth-child(4) {margin-right: 0;
}
.img-li:first-child {margin-right: none;
}
.img-li image {width: 100%;height: 100%;
}

js  最主要部分

Page({/*** 页面的初始数据*/data: {imgList: []},// 点击添加选择chooseSource: function() {var _this = this;wx.showActionSheet({itemList: ["拍照", "从相册中选择"],itemColor: "#CED63A",success: function(res) {if(!res.cancel) {if(res.tapIndex == 0) {_this.imgWShow("camera")        //拍照} else if (res.tapIndex == 1) {_this.imgWShow("album")      //相册}}}})},// 点击调用手机相册/拍照imgWShow: function(type) {var _this = this;let len = 0;if(_this.data.imgList != null) {len = _this.data.imgList.length}   //获取当前已有的图片wx.chooseImage({count: 6-len,     //最多还能上传的图片数,这里最多可以上传5张sizeType: ['original', 'compressed'],        //可以指定是原图还是压缩图,默认二者都有sourceType: [type],             //可以指定来源是相册还是相机, 默认二者都有success: function(res) {wx.showToast({title: '正在上传...',icon: "loading",mask: true,duration: 1000})// 返回选定照片的本地文件路径列表,tempFilePaths可以作为img标签的scr属性显示图片var imgList = res.tempFilePathslet tempFilePathsImg = _this.data.imgList// 获取当前已上传的图片的数组var tempFilePathsImgs = tempFilePathsImg.concat(imgList)_this.setData({imgList: tempFilePathsImgs})},fail: function () {wx.showToast({title: '图片上传失败',icon: 'none'})return;}})},// 预览图片previewImg: function(e) {let index = e.target.dataset.index;let _this = this;wx.previewImage({current: _this.data.imgList[index],urls: _this.data.imgList})},// 点击删除deleteImg: function(e) {var _this = this;var imgList = _this.data.imgList;var index = e.currentTarget.dataset.index;      //获取当前点击图片下标wx.showModal({title: '提示',content: '确认要删除该图片吗?',success: function(res) {if(res.confirm) {console.log("点击确定了")imgList.splice(index, 1);} else if (res.cancel) {console.log("点击取消了");return false}_this.setData({imgList})}})},
})

这里我写了一个限制最多上传6张图片,可以看一下官方文档

更多推荐

微信小程序实现常用添加图片功能, 预览, 删除(完整版)超详细

本文发布于:2024-02-07 04:48:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753280.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:完整版   常用   功能   程序   详细

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!