移动端&小程序处理后端返回的html富文本中图片适应屏幕
互联网 2022/5/10 17:06:47
1 export function handleHtmlImg(string) { 2 var richtext = string; 3 const regex = new RegExp("<img", "gi"); 4 if (richtext != null) { 5 richtext = richtext.replace(regex, `<img style="max-width: 100%;"`); 6 } 7 return richtext 8 }
结果发现有些富文本内图片自带行内样式于是得先清除富文本中自带的样式,再添加max-width:
export function handleHtmlImg(html) { // 先手动清除所有img自带的样式,再手动添加max-width 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%;"'); return newContent; }

关于找一找教程网
本站文章仅代表作者观点,不代表本站立场,所有文章非营利性免费分享。
本站提供了软件编程、网站开发技术、服务器运维、人工智能等等IT技术文章,希望广大程序员努力学习,让我们用科技改变世界。
[移动端&小程序处理后端返回的html富文本中图片适应屏幕]http://www.zyiz.net/tech/detail-319785.html
- 2022-05-270-STM32F407+EC200(移远4G)基本控制篇(自建物联网平台)-整体运行测试-微信小程序扫码绑定EC200,并通过MQTT实现远程通信控制
- 2022-05-27关于微信小程序工具input无法输入的问题
- 2022-05-26微信小程序的内核
- 2022-05-26微信小程序引用vant ui
- 2022-05-26如何调式小程序线上版本
- 2022-05-25微信小程序左右联动
- 2022-05-25微信小程序入门与实战-全新版
- 2022-05-25uniapp小程序使用pont
- 2022-05-24微信小程序 图片转为base64编码
- 2022-05-24微信小程序 wx:for 遍历 Map集合