最近在开发一个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%; }