小程序處理圖片加載失敗的問題


今天在開發西奧程序過程中,遇到一個問題,圖片加載失敗的時候頁面,顯示空白比較難看,需求是希望再圖片加載失敗的時候,顯示加載失敗的圖片,剛開始也查了一番,沒有找到類似的方法,最終自己翻看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 () {

  }
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM