zoukankan      html  css  js  c++  java
  • 微信小程序 rich-text 富文本图片宽度不受控问题

    问题图

    无效代码

    /* 下面代码并不能达到预想效果... */
    rich-text img {
       100%;
      object-fit: contain;
    }
    
    rich-text image {
       100%;
      object-fit: contain;
    }
    

    目标效果图

    util.js

    /**
     * 处理富文本里的图片宽度自适应
     * 1.去掉img标签里的style、width、height属性
     * 2.img标签添加style属性:max-100%;height:auto
     * 3.修改所有style里的width属性为max-100%
     * 4.去掉<br/>标签
     * @param html
     * @returns {void|string|*}
     */
    function formatRichText(html){
        let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
            match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
            match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
            match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
            return match;
        });
        newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
            match = match.replace(/[^;]+;/gi, 'max-100%;').replace(/[^;]+;/gi, 'max-100%;');
            return match;
        });
        newContent = newContent.replace(/<br[^>]*/>/gi, '');
        newContent = newContent.replace(/<img/gi, '<img style="max-100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
        return newContent;
    }
    
    module.exports = {
        formatRichText
    }
    
    

    直接把富文本 html 字段用此方法处理一下即可(等于字符串替换,给图片加上了宽度)

    /* data.des 字段是富文本字段,通过上面的额方法,给 des 中的图片标签加上宽度 */
    wx.request({
        url: urlList.searchLouyu + `?id=${id}`,
        method: "GET",
        success(res) {
            if (res.data.msg == 'success') {
                let data = res.data.list[0]
    
                data.des = util.formatRichText(data.des)
    
                that.setData({
                    listdata: data,
                })
            }
        }
    })
    
  • 相关阅读:
    关于java和jvm的思考
    java之try、catch、finally
    Microsoft SQLServer有四种系统数据库
    HDU 5087
    uva639 暴力、回溯
    uva127
    uva 131
    洛谷 P2580 于是他错误的点名开始了
    字典树(trie)
    HTML学习笔记
  • 原文地址:https://www.cnblogs.com/suwanbin/p/14425306.html
Copyright © 2011-2022 走看看