小程序处理图片加载失败的问题

今天在开发西奥程序过程中,遇到一个问题,图片加载失败的时候页面,显示空白比较难看,需求是希望再图片加载失败的时候,显示加载失败的图片,刚开始也查了一番,没有找到类似的方法,最终自己翻看MDN看到了img的onerror属性,抱着测试的心里,最终解决了自己的问题;在这里记录下来,希望能帮到大家。

下面是处理前和处理后的效果:

<view class="container">
  <block wx:for="{{imgUrls}}" wx:key="index">
    <image src="{{item}}" onerror="imgOnerror" data-idx="{{index}}"></image>
  </block>
</view>
.container {
  display: flex;
  flex-wrap: wrap;
  padding: 30rpx 30rpx 10rpx;
  box-sizing: border-box;
}
.container > image {
  width: 156rpx;
  height: 156rpx;
  background: pink;
  margin: 0 20rpx 20rpx 0;
  display: block;
}
.container > image:nth-of-type(4n) {
  margin-right: 0;
}

  

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [
      'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
      'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=640',
      'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=640',
      'https://images.unsplash.com/photo-1551446666-142875a901a1?w=770',
      'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
      'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
      'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=640',
      'https://images.unsplash.com/photo-1551446666-142875a901a1?w=880',
    ],  //第四和第八张图片是无效的
  },

  /**
   * 图片加载失败处理函数
   */
  imgOnerror(e) {
    var idx = e.currentTarget.dataset.idx;
    console.log(idx)
    var _imgUrls = this.data.imgUrls;
    for (var i = 0; i < _imgUrls.length; i++) {
      if (i == idx) {
        _imgUrls[i] = 'https://images.unsplash.com/photo-1551446591-142875a901a1?w=640'
      }
    }
    this.setData({
      imgUrls: _imgUrls
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
posted @ 2019-07-31 18:08  认真,是一种态度  阅读(3824)  评论(1编辑  收藏  举报