小程序中实现选择预览图片同时可以实现长按删除图片的代码

实现思路:

  • 调整页面,实现展示效果

  • 使用wx.chooseImage实现拍照和选择照片

  • 使用wx.previewImage实现图片预览

  • 使用bindlongpress自定义图片删除功能

话不多说,上代码:
wxml代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<view class="weui-cells">

  <view class="weui-cell">

    <view class="weui-cell__bd">

      <view class="weui-uploader">

        <view class="weui-uploader__hd">

          <view class="weui-uploader__title">图片上传</view>

          <view class="weui-uploader__info">{{files.length}} / 9</view>

        </view>

        <view class="weui-uploader__bd">

          <view class="weui-uploader__files" id="uploaderFiles">

            <block wx:for="{{files}}" wx:key="*this">

              <view class="weui-uploader__file" bindtap="previewImage" bindlongpress="deleteImage" id="{{item}}" data-index="{{index}}">

                <image class="weui-uploader__img" src="{{item}}" mode="aspectFill"/>

              </view>

            </block>

          </view>

          <view wx:if="{{files.length < 9}}" class="weui-uploader__input-box" >

            <view class="weui-uploader__input" bindtap="chooseImage"></view>

          </view>

        </view>

      </view>

    </view>

  </view></view>

js代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

Page({

  data: {

    files: []

  },

  chooseImage: function(e) {

    var that = this;    var images = that.data.files;

    wx.chooseImage({

      count: 9 - images.length,

      sizeType: [‘original‘, ‘compressed‘],

      sourceType: [‘album‘, ‘camera‘],

      success: function(res) {

        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片

        that.setData({

          files: that.data.files.concat(res.tempFilePaths)

        });

      }

    })

  },

  previewImage: function(e) {

    wx.previewImage({

      current: e.currentTarget.id,

      urls: this.data.files

    })

  },

  deleteImage: function(e) {

    var that = this;    var images = that.data.files;    var index = e.currentTarget.dataset.index; //获取当前长按图片下标

    wx.showModal({

      title: ‘系统提醒‘,

      content: ‘确定要删除此图片吗?‘,

      success: function(res) {

        if (res.confirm) {

          images.splice(index, 1);

        } else if (res.cancel) {          return false;

        }

        that.setData({

          files: images

        });

      }

    })

  }

})

小程序中实现选择预览图片同时可以实现长按删除图片的代码

上一篇:微信小程序实例:实现顶部tab切换以及滑动切换时导航栏会随着移动的效果(代码)


下一篇:怎么开发支付宝微信跑分系统源码?码商供码平台搭建回调