引言:在微信小程序里,比如商品展示頁面的商品詳情會有圖片展示,PC端設置的商品詳情是PC端的寬度,所以在小程序里圖片會顯示不全,這時就應該做相應的處理,使小程序里圖片顯示正確
思路
微信小程序需要知道的知識
解決
WXML
<view class='html_detail'> <rich-text nodes='{{artical}}'></rich-text></view>
WXS
data={artical:''}async onLoad(){ const json = await api.getDetail(); if(json !== null){ this.artical = util.formatRichText(json.detail.description); }}
若artical里只有圖片,并且圖片沒有設置style和寬度/高度
util.js
function formatRichText(html){ let newContent= html.replace(//<img/gi, '<img style="max-width:100%;height:auto;display:block;"'); return newContent;}module.exports = { formatRichText}
若artical里包含多種標簽
util.js
/** * 處理富文本里的圖片寬度自適應 * 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, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;'); return match; }); newContent = newContent.replace(/<br[^>]*//>/gi, ''); newContent = newContent.replace(//<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'); return newContent;}module.exports = { formatRichText}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答