先获取数据
//请求数据
news_id_data:function(id){
var that =this
swan.request({
// url:'',
url: 'http://localhost:8080/app/news',
header: { 'content-type': 'application/x-www-form-urlencoded' },
data:{
id:id
},
method:'post',
dataType:"json",
success:function(res){
that.setData({
contentData:res.data,
//替换图片里面的style 相关的样式
content:that.formatRichText(res.data.content)
})
}
});
},
//使用正则表达式替换
//图片自适应
formatRichText:function (html){
let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
return match;
});
newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
return match;
});
newContent = newContent.replace(/<br[^>]*\/>/gi, '');
newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:10px 0;"');
return newContent;
},
使用rich-text插入富编辑器获取的html代码
<rich-text class="content" nodes="{{content}}" image-menu-prevent="true"></rich-text>