微信小程序 rich-text 富文本圖片寬度不受控問題


問題圖

無效代碼

/* 下面代碼並不能達到預想效果... */
rich-text img {
  width: 100%;
  object-fit: contain;
}

rich-text image {
  width: 100%;
  object-fit: contain;
}

目標效果圖

util.js

/**
 * 處理富文本里的圖片寬度自適應
 * 1.去掉img標簽里的style、width、height屬性
 * 2.img標簽添加style屬性:max-width:100%;height:auto
 * 3.修改所有style里的width屬性為max-width: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(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
        return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="max-width: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,
            })
        }
    }
})


免責聲明!

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



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