文前推荐一下👉前端必备工具推荐网站(图床、API和ChatAI、智能AI简历、AI思维导图神器等实用工具):
站点入口:http://luckycola.com.cn/
图床:https://luckycola.com.cn/public/dist/#/imghub
多种API:https://luckycola.com.cn/public/dist/#/
ChatAI:https://luckycola.com.cn/public/dist/#/chatAi
AI思维导图神器:https://luckycola.com.cn/public/dist/#/aiQStore/aiMindPage

小程序解析HTML代码

前言:在一些资讯性的文章需要简单排版时,会用到富文本编辑器,但是富文本编辑器生成的是一些html代码,在小程序中无法使用,下面看看两种解决方法。

一、用微信文档提供的rich-text

<!-->content是API获取的html代码</-->
<rich-text nodes="{{content}}"></rich-text>

*注意:用rich-text不会达到直接想要的结果,比如图片大小最大宽度不是100%,需要自己用js控制

  • 3.下面是处理html样式自适应的代码
/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性:max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉
标签
 */
function formatRichText(html){
    let newContent= html.replace(/]*>/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(/]*\/>/gi, '');
    newContent = newContent.replace(/\, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
    return newContent;
  }
  • 解决完这个,不知道还会有没有其他不可预知的问题,我开发时用的是下一种方法

二、用插件WxParse解析html

  1. 这是GitHub上大神封装的插件,我开发时用的是这个方法,但是作者不维护了,大家选择性用
  2. 先放上下载地址WxParse,或者可以GitHub上直接搜索WxParse,第一个就是
  3. 使用步骤
  • 先下载压缩包
    github下载
  • 然后将文件夹中的wxParse解压到需要的项目中
    拷贝
  • 在项目里引用,分别在js, wxml,wxss引用
    JS:
    js描述
var WxParse = require('../../utils/wxParse/wxParse.js')
...
...
//方法中使用
    getdetaul: function (id) {
           let that = this;
       getDescApi.getdesc(id).then((res) => {
             console.log(res.data);
             that.setData({
               model: res.data,
             });
             WxParse.wxParse("contents", "html", res.data.content, that, 0);
           });
         },

WXML:

<import src="../../utils/wxParse/wxParse.wxml"/>
  <view>
        <template is="wxParse" data="{{wxParseData:contents.nodes}}"/>
  </view>

WXSS:

/* wxss样式引入*/  
@import "../../utils/wxParse/wxParse.wxss";

以上就是小程序解决解析html代码的方法

更多推荐:wantLG的《普歌-码上鸿鹄团队:微信小程序使用阿里巴巴iconfont矢量多色图标


Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐