we-rich 小程序渲染富文本js库
最近項(xiàng)目需要, 把公眾號(hào)的文章直接在小程序顯示, 頁(yè)面除了文章內(nèi)容以外,還有其他組件.
小程序中渲染html, 解決方案有三個(gè)
第一個(gè)方案是由于小程序還沒(méi)有更新2,3的功能時(shí)的一個(gè)臨時(shí)解決辦法. 而使用web-view控件最大問(wèn)題只能整屏顯示.
于是翻閱rich-text控件的文檔說(shuō)明.也是坑滿滿的.
rich-text的控件使用很簡(jiǎn)單, 只需要給nodes屬性賦值要渲染的html節(jié)點(diǎn)數(shù)組或者直接是html代碼即可.
一開(kāi)始想偷懶, 直接在nodes重賦值html代碼. 發(fā)現(xiàn)基本無(wú)法使用. 因?yàn)閞ich-text不支持的標(biāo)簽很多, 遇到不支持的標(biāo)簽(比如section)會(huì)忽略解析.導(dǎo)致很多的html內(nèi)容都會(huì)莫名消失.
只能乖乖的把html代碼變成節(jié)點(diǎn)數(shù)組,然后對(duì)每個(gè)節(jié)點(diǎn)進(jìn)行判斷兼容.
于是有了we-rich這個(gè)庫(kù).
we-rich 直接把html代碼轉(zhuǎn)化成小程序rich-text 可以渲染的nodes節(jié)點(diǎn)
<div class='post post-featured'><p>hello</p><section>world</section><img src="test.png" style="max-width:100%" /></div> 復(fù)制代碼[ {"type": "node","name": "div","attrs": {"class": "post post-featured"},"children": [ {"type": "node","name": "p","attrs": {},"children": [{"type": "text", "text": "hello"} ]}, {"type": "node","name": "div","attrs": {},"children": [{"type": "text", "text": "world"}]}, {"type": "node","name": "img","attrs": {"src": "test.png", "style": "max-width:100%"},"children": []}]} ] 復(fù)制代碼使用辦法
npm install we-richvar weRich = require('we-rich'); var nodes = weRich.parse(html) 復(fù)制代碼轉(zhuǎn)載于:https://juejin.im/post/5a4745b851882538650984c9
總結(jié)
以上是生活随笔為你收集整理的we-rich 小程序渲染富文本js库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2017工作总结
- 下一篇: ios 容错处理JKDataHelper