没格式化之前
图片样式不对:
格式化之后
<view class="content" v-html="formatRichText(data.content)"></view>
formatRichText(html) {
// 富文本内容格式化
return (
html &&
html
.replace(/<img[^>]*>/gi, function (match, capture) {
// 查找所有的 img 元素
return match.replace(/style=".*"/gi, '').replace(/style='.*'/gi, '') // 删除找到的所有 img 元素中的 style 属性
})
.replace(/\<img/gi, '<img style="width:100%;"')
) // 对 img 元素增加 style 属性,并设置宽度为 100%
}
代码
<template>
<view class="container">
<h1>{{ data.title }}</h1>
<view class="info">
<view class="time">{{ getPushTime() }}</view>
<view class="from" v-if="data.source_title != '' && data.source_title != null">来源:{{ data.source_title }}</view>
</view>
<!-- <p class="content"></p> -->
<view class="content" v-html="formatRichText(data.content)"></view>
</view>
</template>
<script>
import { findArticleDetail } from '../../api/home.js'
import { formatTime } from '../../utils/util.js'
export default {
data() {
return {
cdnUrl: getApp().globalData.cdnUrl,
data: {}
}
},
onLoad(options) {
this.getData(options.id)
},
onShow() {},
methods: {
getData: function (id) {
var that = this
findArticleDetail(id).then(function (res) {
that.data = res.data
that.share.title = that.data.title
})
},
getPushTime() {
if (this.data.push_time != '') {
return formatTime(this.data.push_time * 1000, 'YYYY-MM-DD HH:mm:ss')
} else {
return this.data.create_time_text
}
},
formatRichText(html) {
// 富文本内容格式化
return (
html &&
html
.replace(/<img[^>]*>/gi, function (match, capture) {
// 查找所有的 img 元素
return match.replace(/style=".*"/gi, '').replace(/style='.*'/gi, '') // 删除找到的所有 img 元素中的 style 属性
})
.replace(/\<img/gi, '<img style="width:100%;"')
) // 对 img 元素增加 style 属性,并设置宽度为 100%
}
}
}
</script>
<style lang="scss" scoped>
.container {
padding: 33rpx;
font-weight: 400;
color: #333333;
h1 {
font-size: 44rpx;
font-weight: bold;
line-height: 60rpx;
}
.info {
margin-top: 30rpx;
margin-bottom: 30rpx;
font-size: 24rpx;
color: #999999;
display: flex;
justify-content: space-between;
}
.content {
margin-top: 30rpx;
}
}
</style>