引言:在微信小程序里,比如商品展示頁(yè)面的商品詳情會(huì)有圖片展示,PC端設(shè)置的商品詳情是PC端的寬度,所以在小程序里圖片會(huì)顯示不全,這時(shí)就應(yīng)該做相應(yīng)的處理,使小程序里圖片顯示正確
思路
微信小程序需要知道的知識(shí)
解決
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里只有圖片,并且圖片沒(méi)有設(shè)置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里包含多種標(biāo)簽
util.js
/** * 處理富文本里的圖片寬度自適應(yīng) * 1.去掉img標(biāo)簽里的style、width、height屬性 * 2.img標(biāo)簽添加style屬性:max-width:100%;height:auto * 3.修改所有style里的width屬性為max-width:100% * 4.去掉<br/>標(biāo)簽 * @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}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選