uniapp里 rich-text 里的img图片如何控制最大宽度

52 阅读1分钟

uniapp里的富文本展示的时候,要控制里面的图片的最大宽度;
用下面的方法字符串替换,给img标签加个内联样式

<rich-text :nodes="processedDetail(product.product_contents)"></rich-text>

` //处理富文本里的图片宽度限制的样式 processedDetail(html) { if(!html){ return ''; } // 处理方法1: 强制替换所有图片样式 html = html.replace(/<img[^>]>/g, (imgTag) => { // 移除 width 和 height 属性 imgTag = imgTag.replace(/(width|height)=["'][^"']["']/g, '');

		// 处理 style 属性
		if (imgTag.includes('style=')) {
		  // 移除原有的 width/height 样式,添加 max-width
		  imgTag = imgTag.replace(/style=["']([^"']*)["']/, (match, style) => {
			style = style.replace(/(width|height|max-width)[^;]*;?/g, '');
			return `style="${style}max-width: 100% !important; height: auto !important; display: block;"`;
		  });
		} else {
		  // 没有 style 属性,直接添加
		  imgTag = imgTag.replace('<img', '<img style="max-width: 100% !important; height: auto !important; display: block;"');
		}
		
		return imgTag;
	  });
	  
	   return html;
	
}

`