uniapp 富文本图片溢出解决方案

这篇博客介绍了在开发UniApp项目时遇到的富文本img标签样式添加问题。作者首先尝试通过正则表达式在img标签中直接添加style属性,但发现当文本内容的img标签已有style属性且为空时,这种方法会失效。为了解决这个问题,作者提出了第二种方案:使用class代替style,并在CSS中定义`.maximg`类来限制图片最大宽度。这种方法避免了替换原有style属性的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在开发一个uniapp项目的时候遇到一个问题 ,然后在网上收了很多解决大部分都是通过正则 给img 直接添加 样式

通常情况下第一种办法没毛病,但遇到特殊情况就尴尬了,就如 文本内容的标签自带了 style=""属性 并为空 的时候 就把 正则添加的 替换了

也有很多伙伴遇到过这样的问题,所以推荐第二种办法

  • 第一种办法
<template>
 	<view>

 		<view class="shopevaluate">
 			<view class="shopevaluate-goou">
 				<!-- 富文本 start -->
 				<rich-text class='richText' :nodes="neirong"></rich-text>
 				<!-- 富文本 end -->
 			</view>
 		</view>

 	</view>
 </template>

 <script>
 	export default {

 		data() {
 			return {
 				material_id: 0,
 				materialInfo: {},
 				neirong: '',
 			}
 		},
 		onLoad(option) {
 			if (!option.material_id) {
 				uni.showToast({
 					title: '参数错误',
 					icon: 'none'
 				})
 				return false;
 			}
 			this.material_id = option.material_id;
 			this.getdata();
 		},
 		methods: {
 			getdata() {
 				this.$H.post('/Material/materialdetail', {
 					material_id: this.material_id
 				}, {
 					token: true
 				}).then(res => {
 					console.log(res);
 					this.materialInfo = res;
 					this.neirong = res.details_text.replace(/\<img/gi, '<img style="width:100%" ')
 				})
 			},
 		}
 	}
 </script>


  • 第二种办法

<template>
 	<view>

 		<view class="shopevaluate">
 			<view class="shopevaluate-goou">
 				<!-- 富文本 start -->
 				<rich-text class='richText' :nodes="neirong"></rich-text>
 				<!-- 富文本 end -->
 			</view>
 		</view>

 	</view>
 </template>

 <script>
 	export default {

 		data() {
 			return {
 				material_id: 0,
 				materialInfo: {},
 				neirong: '',
 			}
 		},
 		onLoad(option) {
 			if (!option.material_id) {
 				uni.showToast({
 					title: '参数错误',
 					icon: 'none'
 				})
 				return false;
 			}
 			this.material_id = option.material_id;
 			this.getdata();
 		},
 		methods: {
 			getdata() {
 				this.$H.post('/Material/materialdetail', {
 					material_id: this.material_id
 				}, {
 					token: true
 				}).then(res => {
 					console.log(res);
 					this.materialInfo = res;
 					this.neirong = res.details_text.replace(/\<img/gi, '<img class="maximg" ')
 				})
 			},
 		}
 	}
 </script>

 <style>
 
	.maximg{ max-width: 100%; }
	
 </style>



核心代码

js
this.neirong = res.details_text .replace(/<img/gi, '<img class=“maximg”

css
.maximg{ max-width: 100%; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值