uniapp在微信小程序中图片宽度显示问题

在uniapp中,如果你的富文本图片显示宽度不正常,你可以通过设置图片的宽高属性来解决这个问题。例如,你可以在富文本中添加以下代码来设置图片的宽度为100%:

<img src="your_image_url" style="width: 100%" /> 

另外,如果你想设置图片的高度,你可以添加以下代码:

<img src="your_image_url" style="height: 100px" /> 

当然,可以实现一个 filter 来自动对图片宽度进行处理。

export default {
    // ...
    filters: {
        formatRichHtml(html) {
            if (!html) {
                return html;
            }
            //控制小程序中图片大小
            let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
                console.log(match.search(/style=/gi));
                if (match.search(/style=/gi) === -1) {
                    match = match.replace(/\<img/gi, '<img style=""');
                }
                return match;
            });
            newContent = newContent.replace(/style="/gi, '$& max-width:100% !important; ');
            newContent = newContent.replace(/<br[^>]*\/>/gi, '');
            return newContent;
        }
    }
    // ...
}

在调用时只需要如下调用

export default {
    // ...
    filters: {
        formatRichHtml(html) {
            if (!html) {
                return html;
            }
            //控制小程序中图片大小
            let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
                console.log(match.search(/style=/gi));
                if (match.search(/style=/gi) === -1) {
                    match = match.replace(/\<img/gi, '<img style=""');
                }
                return match;
            });
            newContent = newContent.replace(/style="/gi, '$& max-width:100% !important; ');
            newContent = newContent.replace(/<br[^>]*\/>/gi, '');
            return newContent;
        }
    }
    // ...
}

在调用时只需要如下调用即可

<rich-text :nodes="xxxxxContent | formatRichHtml" />
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
105
粉丝
43
喜欢
143
收藏
176
排名:304
访问:3.1 万
私信
所有博文
社区赞助商