Issues with click-to-enlarge and adaptive size of images in the rich-text component of the WeChat applet

in ts file

    
data: {
    // 文本内容
    content:'' ,
    // 图片列表
    imgArr:[]
  },


// 获取富文本内容
  getRichContent(initForm:object){
    getRichContentApi(initForm).then((res:any)=>{
      const { data, msg, result} =res
      if(result==1){
        let mycontent = JSON.parse(JSON.stringify(data.content))
        // 解决图片自适应
        mycontent = mycontent.replace(/\<img/gi, '<img width="100%" height="auto"');
        // 解决图片之间的空隙
        mycontent = mycontent.replace(/style=""/gi, 'style="display:block; width="100%"; height="auto""');

        // 主要代码为后面预览图片准备
        let imgArr = [];
        let regex = new RegExp(/<img.*?(?:>|\/>)/gi); // 匹配所有图片
        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; // 匹配src图片
        let arrsImg = mycontent.match(regex); // mycontent 后台返回的富文本数据
        for (let i = 0; i < arrsImg.length; i++) {
          let srcs = arrsImg[i].match(srcReg);
          imgArr.push(srcs[1])
        }
        this.setData({
          content : mycontent,
          imgArr
        })
      }else{
        wx.showToast({
          title:msg,
          icon:'none'
        })
        this.setData({
          content : ''
        })
      }
    })
  },




  // 点击放大预览图片函数
  catchImage(e:any){
    console.log(this.data.imgArr);
    wx.previewImage({
      current: this.data.imgArr[0], // 当前显示图片的http链接
      urls: this.data.imgArr // 需要预览的图片http链接列表
    })
  },

in wxml file

<rich-text nodes="{
   
   {content}}" space="ensp" catchtap="catchImage"></rich-text>

Guess you like

Origin blog.csdn.net/Achong999/article/details/130802250