1. 程式人生 > >微信小程式圖片上傳放大預覽刪除程式碼

微信小程式圖片上傳放大預覽刪除程式碼

效果:

一,下面是上傳圖片的效果

image.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({
      // count: 1, // 預設9
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
      sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
      success: function (res) {
        // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        // console.log(tempFilePaths + '----');
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgs.length >= 9) {
            that.setData({
              imgs: imgs
            });
            return false;
          } else {
            imgs.push(tempFilePaths[i]);
          }
        }
        // console.log(imgs);
        that.setData({
          imgs: imgs
        });
      }
    });
  },
  // 刪除圖片
  deleteImg: function (e) {
    var that = this;
    var imgs = that.data.imgs;
    var index = e.currentTarget.dataset.index;//獲取當前長按圖片下標
    wx.showModal({
      title: '提示',
      content: '確定要刪除此圖片嗎?',
      success: function (res) {
        if (res.confirm) {
          console.log('點選確定了');
          imgs.splice(index, 1);
        } else if (res.cancel) {
          console.log('點選取消了');
          return false;
        }
        that.setData({
          imgs: imgs
        });
      }
    })
  },
    // 預覽圖片
    previewImg: function (e) {
      //獲取當前圖片的下標
      var index = e.currentTarget.dataset.index;
      //所有圖片
      var imgs = this.data.imgs;

      wx.previewImage({
        //當前顯示圖片
        current: imgs[index],
        //所有圖片
        urls: imgs
      })
    }
})

image.wxml程式碼:

<button class="upload-img-btn" bindtap="chooseImg">上傳</button>
  <view class="img" wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
    <image src="{{item}}" data-index="{{index}}" mode="widthFix" bindtap="previewImg" bindlongpress="deleteImg"></image>
  </view>

有問題,隨時聯絡,郵箱地址:[email protected],留言也行的哦