欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序?qū)崿F(xiàn)富文本圖片寬度自適應的方法

 更新時間:2019年01月20日 11:36:09   作者:孟小歡  
小程序里圖片會顯示不全,這時就應該做相應的處理,使小程序里圖片顯示正確,這篇文章主要介紹了微信小程序?qū)崿F(xiàn)富文本圖片寬度自適應的方法,感興趣的小伙伴們可以參考一下

引言:在微信小程序里,比如商品展示頁面的商品詳情會有圖片展示,PC端設置的商品詳情是PC端的寬度,所以在小程序里圖片會顯示不全,這時就應該做相應的處理,使小程序里圖片顯示正確

思路

  • 把圖片的寬度改為手機屏幕對應的寬度

微信小程序需要知道的知識

  • 需要知道微信小程序里有自己的寬度標準,單位為rpx;
  • 針對所有不同尺寸的瀏覽器,微信小程序里規(guī)定屏幕寬為750rpx;

解決

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
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論