rich-text的使用
rict-text可以支持部分HTML節(jié)點及屬性
rict-text的屬性如下:
nodes 值為 HTML String 時,在組件內部將自動解析為節(jié)點列表,推薦直接使用 Array 類型避免內部轉換導致的性能下降。App-nvue 和支付寶小程序不支持 HTML String 方式,僅支持直接使用節(jié)點列表即 Array 類型,如要使用 HTML String,則需自己將 HTML String 轉化為 nodes 數(shù)組,可使用 html-parser (opens new window)轉換。
例如:
<rich-text nodes="{{htmlSnip}}"></rich-text>
htmlSnip: [{
name: 'div',
attrs: {
class: 'div-class',
style: 'line-height: 60px; color: red; text-align:center;'
},
children: [{
type: 'text',
text: 'Hello uni-app!'
}]
}],
有時候展現(xiàn)的圖片也是沒有樣式的,導致圖片會按照原始大小顯示,超出界面框架。我們需要用正則將內容轉義一下:
新建一個js文件 replaceImg.js:文章來源:http://www.zghlxwxcb.cn/news/detail-538326.html
/**
* 處理富文本里的圖片寬度自適應
* 1.去掉img標簽里的style、width、height屬性
* 2.img標簽添加style屬性:max-width:100%;height:auto
* 3.修改所有style里的width屬性為max-width:100%
* 4.去掉<br/>標簽
* @param html
* @returns {void|string|*}
*/
function formatRichText(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;
}
// module.exports = {
// formatRichText
// }
module.exports = {
formatRichText: formatRichText
}
在對應的界面調用:文章來源地址http://www.zghlxwxcb.cn/news/detail-538326.html
var replace_img = require("../../../utils/replaceImg.js");
//request
let data_article = res.data.data[0];//這里是請求到的 html 內容
var newsArticle = replace_img.formatRichText(data_article.content);
that.setData({
art_content:newsArticle
});
到了這里,關于【uni-app】rich-text的使用的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!