本文实例讲述了微信小程序rich-text富文本用法。分享给大家供大家参考,具体如下:
rich-text是一个新增的微信小程序插件,从基础库1.4.0开始,低版本需要做兼容处理
nodes属性可为Array和String类型,但推荐使用Array.由于String类型最终也会转为Array类型
nodes分为支持两种节点,分别为元素节点(type=node ,默认为元素节点)和文本节点(type=text)
元素节点
name |
标签名 |
String |
是 |
支持部分受信任的HTML节点 |
attrs |
属性 |
Object |
否 |
支持部分受信任的属性,遵循Pascal命名法 |
children |
子节点列表 |
Array |
否 |
结构和nodes一致 |
- <!-- rich-text.wxml -->
- <rich-text nodes="{{nodes}}" bindtap="tap"></rich-text>
- <!--{{nodes}}其中的变量名与data中名字相同-->
- <!--支持默认事件tap、touchstart、touchmove、touchcancel、touchend和longtap-->
-
- // rich-text.js
- Page({
- data: {
- nodes: [{
- name: 'div',
- attrs: {
- class: 'div_class',
- style: 'width : 100px; height : 100px; color: red;'
- },
- children: [{
- type: 'text',
- text: 'Hello World!'
- }]
- }]
- },
- tap() {
- console.log('tap')
- }
- })
-
如果页面中存在多个富文本,富文本中存在多个孩子,请看下例:
- <!-- rich-text.wxml -->
- <rich-text nodes="{{nodes}}"></rich-text>
- <rich-text nodes="{{nodes1}}"></rich-text>
-
- // rich-text.js
- Page({
- data: {
- nodes: [{
- name: 'div',
- attrs: {
- class: 'div_class',
- style: 'width : 100px; height : 100px; color: red;'
- },
- children: [{
- type: 'text',
- text: 'Hello World!'
- }]
- }],
- nodes1: [{
- name: 'p',
- attrs: {
- class: 'p_class',
- style: 'text-align : center; color: green;'
- },
- children: [{
- type: 'text',
- text: '我是p标签!!!'
- },{
- name: "span",
- attrs: {
- style: "color:red",
- class: "span_class"
- },
- children: [{
- type: "text",
- text: '我是span标签,哈哈哈哈'
- }]
- }]
- }]
- },
- })
-
文本节点
text |
文本 |
String |
是 |
支持entities |
- <!-- rich-text.wxml -->
- <rich-text nodes="{{nodes}}"></rich-text>
-
- // rich-text.js
- Page({
- data: {
- nodes: "我是文本节点,意外不?"
- },
- })
-
注意:
- 全局支持class和style属性,不支持id属性。
- nodes 不推荐使用 String 类型,性能会有所下降
- rich-text 组件内屏蔽所有节点的事件。
- name 属性大小写不敏感
- 如果使用了不受信任的HTML节点,该节点及其所有子节点将会被移除,受信任的html节点请看官方文档
- img 标签仅支持网络图片
希望本文所述对大家微信小程序开发有所帮助。