小程序上显示富文本

  • 功能:富文本内容格式化、拿到富文本里的所有图片点击放大图片

  • util.ts

    export function formatRichText(html: any) { // 富文本内容格式化
    let arrText = html;
    //正则匹配不含style="" 或 style='' 的img标签
    var regex1 = new RegExp("(i?)(<img)(?!(.?style='"['"])[^>]+>)", "gmi");
    //给不含style="" 或 style='' 的img标签加上style=""
    arrText = arrText.replace(regex1, "$2 style=""$3");
    //正则匹配含有style的img标签
    var regex2 = new RegExp("(i?)(<img.
    ?style=['"])([^>]+>)", "gmi");
    //在img标签的style里面增加css样式(这里增加的样式:width:100%😉
    arrText = arrText.replace(regex2, "$2width:100%;$3");
    // 正则表达式 全局匹配 table tr td标签,并给各自标签添加class类名
    arrText = arrText.replace(/<table/g, '<table class="table-rich"')
    arrText = arrText.replace(/<tr/g, '<tr class="table-tr"')
    arrText = arrText.replace(/<td/g, '<td class="table-td"')
    return arrText
    }

  • 使用 index.ts

    import { formatRichText } from "../util";
    data: {
    content: '',
    imgArr: []
    },
    onLoad(options: any) {
    this.getData();
    },
    getData() {
    const res = '富文本编辑器内容'
    const data = formatRichText(res);
    // 主要代码为后面预览图片准备
    let imgArr: any = [];
    let regex = new RegExp(/<img.?(?:>|/>)/gi); // 匹配所有图片
    let srcReg = /src=['"]?([^'"]
    )['"]?/i; // 匹配src图片
    let arrsImg = data.match(regex); // data后台返回的富文本数据
    if (arrsImg && arrsImg.length > 0) {
    for (let i = 0; i < arrsImg.length; i++) {
    let srcs = arrsImg[i].match(srcReg);
    imgArr.push(srcs[1])
    }
    }
    this.setData({
    content: data,
    imgArr
    })
    console.log(data) // 富文本内容
    console.log(imgArr) // 图片数组

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

  • index.wxml

posted @ 2024-04-17 10:11  不完美的完美  阅读(657)  评论(0)    收藏  举报