1. uniapp 富文本rich-text 文本首行縮進和圖片居中
1.1. rich-text 文本首行縮進
??使用 rich-text 組件渲染html格式的代碼,常常因為不能自定義css導致文本不能縮進,以及圖片不能居中等問題,這里可以考慮使用js的replace方法,替換字符串,然后在渲染的同時加載行內樣式。
//頁面上加載
<rich-text :nodes="goodsDetail.detail"></rich-text>
var richtext= this.goodsDetail.detail;
const regex = new RegExp('<img', 'gi');
richtext = richtext.replace(regex, `<img style="max-width:100%;height:auto;display:block;"`);
this.goodsDetail.detail = richtext;
??replace里的g表示全局替換,而每個關鍵詞前面的\則為轉義字符,在針對html類的標簽替換的時候,是必不可少的。這個方法還支持拓展關鍵詞增加如果有需求可以自行添加,需要自定義的css樣式則可以在所替換的字符串關鍵詞里定義。
1.2. 富文本圖片居中
1.2.1. 問題
??uni-app - 完美解決 rich-text 富文本解析圖片無法自適應寬高問題,圖片超出屏幕寬度且不受控。
1.2.2. 解決方案
??對顯示前的富文本數據,使用正則進行替換處理圖片標簽,加入自適應屬性樣式。
<rich-text :nodes="repairRichText('<b>您的富文本內容</b>')" />
/*** 修復富文本圖片寬度* @description 解決圖片寬高超出顯示不全問題(讓其自適應)* @param {String} html - 富文本* @return String*/
repairRichText(html) {// 去掉<img>中style /width / height屬性let newContent = html.replace(/<img[^>]*>/gi, (match) => {match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')// 去除 style=""這樣的屬性(非必須,不需要可自行注釋)match = match.replace(/style\s*=\s*(["'])(?:(?!\1).)*\1/gi, '')return match})// 修改所有style里的width屬性為max-width:100%newContent = newContent.replace(/style="[^"]+"/gi, (match) => {match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;')return match})// 去掉所有<br/>標簽newContent = newContent.replace(/<br[^>]*\/>/gi, '')// img標簽添加style屬性:max-width:100%;height:autonewContent = newContent.replace(/\<img/gi,'<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"')// returnreturn newContent;
}