小程序點擊圖片放大實現方式:使用微信小程序圖片預覽接口。
今天用到了上傳圖片的功能,在真機上測試時發現有的圖片實際沒有顯示,有個小小的坑,分享出來,希望大家可以避免。共勉!
wxml:
<button bindtap="addPic">添加圖片</button> <view class="imgBox" wx:for="{{imgBox}}" wx:key="index"> <image src="{{item}}" data-src="{{item}}" mode="aspectFill" bindtap="previewImage"></image> </view>
wxss:
.imgBox{width:300rpx;height:300rpx; float: left; margin:0 20rpx;} .imgBox image { width:100%;height:100%;}
js:
Page({ data: { imgBox:[], }, addPic:function(){ var _this=this; var imgBox=[]; wx.chooseImage({ count: 4, // 默認9 sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有 sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有 success: function (res) { // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片 var tempFilePaths = res.tempFilePaths; for (var i = 0; i < tempFilePaths.length;i++){ imgBox.push(tempFilePaths[i]); } _this.setData({ imgBox: _this.data.imgBox.concat(imgBox) }) } }) }, previewImage: function (e) { wx.previewImage({ current: e.currentTarget.dataset.src, // 當前顯示圖片的http鏈接 urls: this.data.imgBox // 需要預覽的圖片http鏈接列表 }) }, })
手動設置圖片就不贅述了,就是設置imgBox,這里只用真機測試,取實際的圖片。
在這里要注意,res.tempFilePaths實際返回的是一個數組,在選擇多張圖片時,數組的長度就是實際選擇的照片張數,必須要進行循環,拿到全部的數據,頁面圖片才能正常全部顯示。
