小程序默认是不支持html格式的内容显示的,那我们需要显示html内容的时候,就可以通过wxParse来实现。
1、下载wxParse文件
git地址:https://github.com/icindy/wxParse
- wxParse/
-wxParse.js(必须存在)
-html2json.js(必须存在)
-htmlparser.js(必须存在)
-showdown.js(必须存在)
-wxDiscode.js(必须存在)
-wxParse.wxml(必须存在)
-wxParse.wxss(必须存在)
-emojis(可选)
2、将其中的wxparse复制到小程序的项目中(与pages同级目录)
3、在app.wxss全局样式文件中,需要引入wxParse的样式表
@import "wxParse/wxParse.wxss";
4、在需要加载html内容的页面对应的js文件里引入wxParse
var WxParse = require('../../wxParse/wxParse.js');
5、通过调用WxParse.wxParse方法来设置html内容
var article = '<div>我是HTML代码</div>';
/**
* WxParse.wxParse(bindName , type, data, target,imagePadding)
* 1.bindName绑定的数据名(必填)
* 2.type可以为html或者md(必填)
* 3.data为传入的具体数据(必填)
* 4.target为Page对象,一般为this(必填)
* 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
*/
var that = this;
WxParse.wxParse('article', 'html', article, that, 5);
例:
data: {
dkheight:300,
dkcontent: "你好<br/>nihao, <br/><br/><br/><br/><br/><br/><br/>这个是测试<br/><br/>你同意了吗<br/><br/><br/>hehe<b>n你好啊,我加粗了kk</b >",
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
// 获得高度
let winPage = this;
wx.getSystemInfo({
success: function (res) {
let winHeight = res.windowHeight;
console.log(winHeight);
winPage.setData({
dkheight: winHeight - winHeight*0.05 - 80
})
}
})
wxparse.wxParse('dkcontent', 'html', this.data.dkcontent, this, 5);
},
效果:
6.在页面中引用模板
// 引入模板
<import src="你的路径/wxParse/wxParse.wxml"/>
//这里data中article为bindName
<template is="wxParse" data="{{wxParseData:article.nodes}}"/>
例:
<import src="../../wxParse/wxParse.wxml"/>
<view class='page'>
<view class='page__title dk-title'>显示html格式</view>
<view class="page__bd page__bd_spacing">
<view class='dk-show' style='height:{{dkheight}}px;'>
<template is="wxParse" data="{{wxParseData:dkcontent.nodes}}"/>
</view>
</view>
</view>
实例:
app.wxss
@import "/page/wxParse/wxParse.wxss";
view.js
var WxParse = require('../../wxParse/wxParse.js');
Page({
data: {
},
onLoad: function () {
var that = this;
wx.request({
url: '',
method: 'POST',
data: {
'id':13
},
header: {
'content-type': 'application/json'
},
success: function(res) {
var article = res.data[0].post;
WxParse.wxParse('article', 'html', article, that,5);
}
})
}
})
view.wxml
<import src="../../wxParse/wxParse.wxml"/>
<template is="wxParse" data="{{wxParseData:article.nodes}}"/>
转载请注明: ITTXX.CN--分享互联网 » 小程序中显示html富文本的方法
最后更新:2020-06-02 18:20:24