uniapp开发支付宝小程序/微信小程序时,显示富文本文件 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 小程序相关 >

uniapp开发支付宝小程序/微信小程序时,显示富文本文件

发表时间:2020-10-14

发布人:葵宇科技

浏览次数:102

微信

<!-- #ifndef MP-ALIPAY -->
 	<view class="detailsContent"  v-html="imgStyle(details.text)">
  	 </view>
<!-- #endif -->
imgStyle(val){
	if(val!=''&&val!=undefined&&val!=null){
		return val?.replace(/<img/g, '<img style="max-width: 100%!important;display: block;margin: 0 auto;"')
	}else{
		return val;
	}
},

支付宝

 <!-- #ifdef MP-ALIPAY -->
	<rich-text :nodes="changeText(details.text)"></rich-text>
	<!-- #endif -->
/**支付宝处理富文本文件*/
	changeText(html){
		/**
		 * 处理富文本里的图片宽度自适应
		 * 1.去掉img标签里的style、width、height属性
		 * 2.img标签添加style属性:max-width:100%;height:auto
		 * 3.修改所有style里的width属性为max-width:100%
		 * 4.去掉<br/>标签
		 * @param html
		 * @returns {void|string|*}
		 */
		if(html!=''&&html!=undefined&&html!=null){
		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;"');
		//将 HTML String转化为 nodes 数组
		const content = new HTMLParser(newContent.replace()?.trim());
		return content;
		}else{
			return html;
		}
	}

用到的类库 html-parser.js

相关案例查看更多