前端實現圖片預覽的兩種方式及使用


A.URL.createObjectURL

     就是將用戶通過文件上傳表單元素,所選擇的圖片 讀取到內存當中

     並且返回這個圖片的url地址,將來就可以將url地址設置給src屬性用來展示圖片

 

    createObjectURL 方法的特點就是他的執行方法是同步的

B.FileReader 對象

    使用FileReader對象讀取文件上傳表單元素,選擇的圖片,並且生成一個base64的字符將來就可以將base64的字符串設置給圖片的src屬性,用來做圖片的預覽

    FileReader對象的使用特點就是執行方式是異步的

 另一種方法詳解

  有了方法但是我們先從需求分析:實現思路

  1. 從文章內容中獲取到所有的 img DOM 節點

  2. 獲取文章內容中所有的圖片地址

  3. 遍歷所有 img 節點,給每個節點注冊點擊事件

  4. img 點擊事件處理函數中,調用 ImagePreview 預覽

     我們運用了vant-ui組件中的ImagePreview 圖片預覽

import { ImagePreview } from 'vant'  
// 按需加載 全局加載不需要寫 我這里寫是為了突出方法 ImagePreview
 ImagePreview(['https://img.yzcdn.cn/vant/apple-1.jpg'])  // 直接運用方法

正文: 

1.給文章詳情元素綁定 ref 屬性

<div ref="article-content" class="article-content" v-html="article.content"></div>

2.封裝 ImagePreview 預覽圖片方法

// 預覽圖片
previewImage() {
  // 得到所有的 img 節點
  const articleContent = this.$refs['article-content']
  const imgs = articleContent.querySelectorAll('img')
  const images = []

  imgs.forEach((item, index) => {
    images.push(item.src)

    item.onclick = () => {
      ImagePreview({
        images: images,
        startPosition: index
      })
    }
  })
}

3.在頁面加載成功中,調用 ImagePreview 預覽方法

setTimeout(() => {
  this.previewImage()
})

  完畢!

 


免責聲明!

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



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