小程序 rich-text 富文本

做项目过程中,经常遇到接口里传过来的内容是包含html标签的,但是样式又不全面,导致在小程序显示的时候,整个界面都是乱的。
这时候就要用到rich-text

rich-text

使用:

<!--wxml-->
<rich-text nodes="{{htmlSnip}}"></rich-text>

有时候展现的图片也是没有样式的,导致图片会按照原始大小显示,超出界面框架。我们需要用正则将内容转义一下:
新建一个js文件 replaceImg.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, '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
}

在对应的界面调用:

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
});

可以在小程序内尝试打印看看获取到的最后的内容;


图片

这时候的img标签已经被加上的style。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容