小程序富文本图片自适应

  1. 从接口里获取到的文本:
<img alt="" src="http://地址.jpg" height="237" width="550" style="height:auto;" /> 
  1. 尝试了很多种修改图片样式的方法:
this.nodes= htmlString .replace(/<img/gi, '<img width="80%!important" ')
//this.nodes= htmlString .replace(/<img/gi, '<img style="max-width:100%!important;height:auto;display:block" ')
  1. 正则替换后的文本:
<img width="80%!important"  alt="" src="http://地址.jpg" height="237" width="550" style="height:auto;" /> 
  1. 不生效,好气~

  2. 翻官方文档发现:
    在这里插入图片描述

    nodes 不推荐使用 String 类型,性能会有所下降

  3. 哎, 好吧 好气~

  4. HTML String 转成 节点列表

  5. 安装 npm install mini-html-parser2 --save

  6. 引用 import parse from 'mini-html-parser2';

  7. 调用:

    const content = htmlString.replace(/<img/gi, '<img width="80%!important" ')
    	// htmlString是从接口里得到的富文本内容
    parse(content, (err, nodes) => {
    	if (!err) {
    		this.nodes = nodes
    	}
    })
    
  8. ok 大功告成,开心

  9. 教训: 一出bug只想着搜答案,多看看官方文档,OK?

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值