使用uni-app写小程序,解析含有html标签的富文本
最近在改一个项目,将html+js+css的项目改成小程序,我说使用的uni来写的,其中遇到一个问题,就是需要解析富文本,在vue中可以直接使用v-html,
但是小程序中的标签都是view,text以及image等,该怎么办呢
于是在uni官网找到插件u-parse
1 | <u-parse :content= 'dangquestion.question' className= 'texttitle' :imageProp= 'imageProp' ></u-parse> |
dangquestion.question是需要展示的富文本字符串,texttitle是类名,可以自己写样式,imageProp,是图片样式,,格式如下
1 2 3 4 5 6 | imageProp:{ mode: 'aspectFit' , domain: '图片的服务器根域名' , //富文本中图片一般是'upload/img/1.png' padding:10, lazyLoad: false }, |
于是下载引用,但是发现一个问题,图片不能完好的展示,并且在span,img标签外包裹一层view标签,使页面不能完全按照富文本展示
后来发现有一个很好的用法
1 | <rich-text :nodes= "content" class = "texttitle" ></rich-text> |
texttitle是自己定义的样式,content是需要展示的富文本字符串
content需要自己先解析一下,如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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:inline-block;margin:10rpx auto;"' ); return newContent; } |
html是传递的参数,就说包含html标签的富文本,如下
let str='<p><span style=\"color: rgb(0, 0, 0); font-size: 16px;\"><strong>女,28岁。</strong></span></p>'
想要获取content需要 this.content=this.formatRichText(str)
根据以上,带入相应参数即可,可以完美展示富文本,图片大小也可根据富文本样式一比一展示。
完结。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了