小程序点击图片放大

784 阅读1分钟

知识点

  • 小程序中有提供api, wx.previewImage(object,object)
  • 在新页面中全屏预览图片。预览的过程中用户可以进行保存图片、发送给朋友等操作。
属性 类型 说明
urls array 需要预览的图片链接数组
current string 当前图片的链接
success function 成功回调
fail function 失败回调
complte function 结束回掉(成功、失败都可以)
  • 示例代码
wx.previewImage({
  current: '',  // 当前显示图片的http链接
  urls: []      // 需要预览的图片http链接列表
})

项目问题

一维数组中使用这个api是很方便的

二维数组中使用这个api

  • js
data: {
    newsList:[
      {
        id:'1',
        imgs:[
          'https://api-hmugo-web.itheima.net/pyg/banner1.png',
          'https://api-hmugo-web.itheima.net/pyg/banner2.png',
          'https://api-hmugo-web.itheima.net/pyg/banner3.png'
        ]
      },
      {
        id:'2',
        imgs:[
          'https://api-hmugo-web.itheima.net/pyg/banner2.png',
          'https://api-hmugo-web.itheima.net/pyg/banner1.png',
          'https://api-hmugo-web.itheima.net/pyg/banner3.png'
        ]
      },
      {
        id:'3',
        imgs:[
          'https://api-hmugo-web.itheima.net/pyg/banner3.png',
          'https://api-hmugo-web.itheima.net/pyg/banner2.png',
          'https://api-hmugo-web.itheima.net/pyg/banner1.png'
        ]
      }
        
    ]
  },
        
/*
    图片点击放大

  * @param index 当前图片的下标
  * @param item  当前点击对象的所有图片链接
  */
//  12123
  previewImg:function(e){
    let index = e.currentTarget.dataset.index; 
    let item = e.currentTarget.dataset.item;    
    wx.previewImage({
      current: item[index],     
      urls: item,               
    })
  }

当点击事件被触发的时候,会把当前数据中的图片链接通过data-item全部传递给js去处理。cuurent存放的是当前的链接地址、urls存放的是全部链接的数组。

  • wxml
<view class="event-row" wx:for="{{newsList}}" wx:key="{{id}}">
        <view class="event-item">
            <view class="title-row">
                <view class="title">{{item.title}}</view>
                <text class="title-content" >
                    {{item.content}}
                </text>
                <view class="img">
                    <image class=""  wx:for="{{item.imgs}}" wx:for-item="item02" src="{{item02}}" data-item="{{item.imgs}}" data-index="{{index}}" bindtap="previewImg"
                    ></image> 
                </view>
            </view>
        </view>
    </view>

应该是这个api的bug,如果图片链接重复,他显示分页就会显示第一次出现的页数

如图:

一样的链接它会一直跳到 1/5 第一张