小程序富文本rich-text组件渲染 img 样式修改问题

在开发时,要用到将富文本编辑器中的内容渲染到页面,涉及图片样式的修改,尝试了直接更改样式,发现并没有效果,这是因为原有富文本编辑器中的图片原有样式级别更高,后面加的样式不能够覆盖原有的样式,需要先将元素原有样式清除,再重新增加新的样式,整理如下:

<!-- index.wxml -->
<view class="detailBox">
	<rich-text class="detailContent" nodes='{
     
     {htmlSnip}}'></rich-text>
</view>
/* index.js */
Page({
    
    
	data:{
    
    
	   htmlSnip:''
	},
	clickDetail(e){
    
    
		var item = e.currentTarget.dataset.item;
		const htmlSnip = item.prizeDescription;	
		//先清除原有样式
	    let newhtml = htmlSnip.replace(/<img[^>]*>/gi, function (match, capture) {
    
    
	      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');	      
	      return match;
	    });	 
	    //再设置新的样式  
	    newhtml = newhtml.replace(/\<img/gi, '<img style="max-width:60%;height:auto;text-align:center;"');	
	    this.setData({
    
    
	      htmlSnip: newhtml
	    })
	 }
 })

同样,其他标签的也可通过以上方式修改样式,小伙伴们可以尝试一下

关于rich-text组件的用法可查看官方文档:rich-text官方文档
关于replace的用法可参考:replace的用法总结

猜你喜欢

转载自blog.csdn.net/qq_38970408/article/details/127735902