当前位置:网站首页>Wechat applet rich text picture width height adaptive method introduction (rich text)

Wechat applet rich text picture width height adaptive method introduction (rich text)

2022-06-24 10:24:00 Wandering in memory of Yu Fei

Wechat applet rich-text The method of adaptive width and height of rich text pictures

Invalid code

/*  The following code does not work as expected ... */
rich-text img {
    
  width: 100%;
  object-fit: contain;
}
 
rich-text image {
    
  width: 100%;
  object-fit: contain;
}

encapsulation util.js

/** *  Adaptive processing of image width in rich text  * 1. Get rid of img Inside the label style、width、height attribute  * 2.img add style attribute :max-width:100%;height:auto * 3. Modify all style Inside width The attribute is max-width:100% * 4. Get rid of <br/> label  * @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
}
 

Put rich text directly html Fields can be processed in this way ( Equals string substitution , Added width to the picture )

/* data.des  Fields are rich text fields , Through the above method , to  des  Add width to the picture label in  */
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,
            })
        }
    }
})
原网站

版权声明
本文为[Wandering in memory of Yu Fei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240914529120.html