jyf-parser.vue 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. <<<<<<< HEAD
  2. <template>
  3. <view>
  4. <slot v-if="!nodes.length" />
  5. <!--#ifdef APP-PLUS-NVUE-->
  6. <web-view id="_top" ref="web" :style="'margin-top:-2px;height:'+height+'px'" @onPostMessage="_message" />
  7. <!--#endif-->
  8. <!--#ifndef APP-PLUS-NVUE-->
  9. <view id="_top" :style="showAm+(selectable?';user-select:text;-webkit-user-select:text':'')">
  10. <!--#ifdef H5 || MP-360-->
  11. <div :id="'rtf'+uid"></div>
  12. <!--#endif-->
  13. <!--#ifndef H5 || MP-360-->
  14. <trees :nodes="nodes" :lazyLoad="lazyLoad" :loading="loadingImg" />
  15. <!--#endif-->
  16. </view>
  17. <!--#endif-->
  18. </view>
  19. </template>
  20. <script>
  21. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  22. import trees from './libs/trees';
  23. var cache = {},
  24. // #ifdef MP-WEIXIN || MP-TOUTIAO
  25. fs = uni.getFileSystemManager ? uni.getFileSystemManager() : null,
  26. // #endif
  27. Parser = require('./libs/MpHtmlParser.js');
  28. var dom;
  29. // 计算 cache 的 key
  30. function hash(str) {
  31. for (var i = str.length, val = 5381; i--;)
  32. val += (val << 5) + str.charCodeAt(i);
  33. return val;
  34. }
  35. // #endif
  36. // #ifdef H5 || APP-PLUS-NVUE || MP-360
  37. var windowWidth = uni.getSystemInfoSync().windowWidth,
  38. cfg = require('./libs/config.js');
  39. // #endif
  40. // #ifdef APP-PLUS-NVUE
  41. var weexDom = weex.requireModule('dom');
  42. // #endif
  43. /**
  44. * Parser 富文本组件
  45. * @tutorial https://github.com/jin-yufeng/Parser
  46. * @property {String} html 富文本数据
  47. * @property {Boolean} autopause 是否在播放一个视频时自动暂停其他视频
  48. * @property {Boolean} autoscroll 是否自动给所有表格添加一个滚动层
  49. * @property {Boolean} autosetTitle 是否自动将 title 标签中的内容设置到页面标题
  50. * @property {Number} compress 压缩等级
  51. * @property {String} domain 图片、视频等链接的主域名
  52. * @property {Boolean} lazyLoad 是否开启图片懒加载
  53. * @property {String} loadingImg 图片加载完成前的占位图
  54. * @property {Boolean} selectable 是否开启长按复制
  55. * @property {Object} tagStyle 标签的默认样式
  56. * @property {Boolean} showWithAnimation 是否使用渐显动画
  57. * @property {Boolean} useAnchor 是否使用锚点
  58. * @property {Boolean} useCache 是否缓存解析结果
  59. * @event {Function} parse 解析完成事件
  60. * @event {Function} load dom 加载完成事件
  61. * @event {Function} ready 所有图片加载完毕事件
  62. * @event {Function} error 错误事件
  63. * @event {Function} imgtap 图片点击事件
  64. * @event {Function} linkpress 链接点击事件
  65. * @author JinYufeng
  66. * @version 20200728
  67. * @listens MIT
  68. */
  69. export default {
  70. name: 'parser',
  71. data() {
  72. return {
  73. // #ifdef H5 || MP-360
  74. uid: this._uid,
  75. // #endif
  76. // #ifdef APP-PLUS-NVUE
  77. height: 1,
  78. // #endif
  79. // #ifndef APP-PLUS-NVUE
  80. showAm: '',
  81. // #endif
  82. nodes: []
  83. }
  84. },
  85. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  86. components: {
  87. trees
  88. },
  89. // #endif
  90. props: {
  91. html: String,
  92. autopause: {
  93. type: Boolean,
  94. default: true
  95. },
  96. autoscroll: Boolean,
  97. autosetTitle: {
  98. type: Boolean,
  99. default: true
  100. },
  101. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  102. compress: Number,
  103. loadingImg: String,
  104. useCache: Boolean,
  105. // #endif
  106. domain: String,
  107. lazyLoad: Boolean,
  108. selectable: Boolean,
  109. tagStyle: Object,
  110. showWithAnimation: Boolean,
  111. useAnchor: Boolean
  112. },
  113. watch: {
  114. html(html) {
  115. this.setContent(html);
  116. }
  117. },
  118. created() {
  119. // 图片数组
  120. this.imgList = [];
  121. this.imgList.each = function(f) {
  122. for (var i = 0, len = this.length; i < len; i++)
  123. this.setItem(i, f(this[i], i, this));
  124. }
  125. this.imgList.setItem = function(i, src) {
  126. if (i == void 0 || !src) return;
  127. // #ifndef MP-ALIPAY || APP-PLUS
  128. // 去重
  129. if (src.indexOf('http') == 0 && this.includes(src)) {
  130. var newSrc = src.split('://')[0];
  131. for (var j = newSrc.length, c; c = src[j]; j++) {
  132. if (c == '/' && src[j - 1] != '/' && src[j + 1] != '/') break;
  133. newSrc += Math.random() > 0.5 ? c.toUpperCase() : c;
  134. }
  135. newSrc += src.substr(j);
  136. return this[i] = newSrc;
  137. }
  138. // #endif
  139. this[i] = src;
  140. // 暂存 data src
  141. if (src.includes('data:image')) {
  142. var filePath, info = src.match(/data:image\/(\S+?);(\S+?),(.+)/);
  143. if (!info) return;
  144. // #ifdef MP-WEIXIN || MP-TOUTIAO
  145. filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.${info[1]}`;
  146. fs && fs.writeFile({
  147. filePath,
  148. data: info[3],
  149. encoding: info[2],
  150. success: () => this[i] = filePath
  151. })
  152. // #endif
  153. // #ifdef APP-PLUS
  154. filePath = `_doc/parser_tmp/${Date.now()}.${info[1]}`;
  155. var bitmap = new plus.nativeObj.Bitmap();
  156. bitmap.loadBase64Data(src, () => {
  157. bitmap.save(filePath, {}, () => {
  158. bitmap.clear()
  159. this[i] = filePath;
  160. })
  161. })
  162. // #endif
  163. }
  164. }
  165. },
  166. mounted() {
  167. // #ifdef H5 || MP-360
  168. this.document = document.getElementById('rtf' + this._uid);
  169. // #endif
  170. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  171. if (dom) this.document = new dom(this);
  172. // #endif
  173. // #ifdef APP-PLUS-NVUE
  174. this.document = this.$refs.web;
  175. setTimeout(() => {
  176. // #endif
  177. if (this.html) this.setContent(this.html);
  178. // #ifdef APP-PLUS-NVUE
  179. }, 30)
  180. // #endif
  181. },
  182. beforeDestroy() {
  183. // #ifdef H5 || MP-360
  184. if (this._observer) this._observer.disconnect();
  185. // #endif
  186. this.imgList.each(src => {
  187. // #ifdef APP-PLUS
  188. if (src && src.includes('_doc')) {
  189. plus.io.resolveLocalFileSystemURL(src, entry => {
  190. entry.remove();
  191. });
  192. }
  193. // #endif
  194. // #ifdef MP-WEIXIN || MP-TOUTIAO
  195. if (src && src.includes(uni.env.USER_DATA_PATH))
  196. fs && fs.unlink({
  197. filePath: src
  198. })
  199. // #endif
  200. })
  201. clearInterval(this._timer);
  202. },
  203. methods: {
  204. // 设置富文本内容
  205. setContent(html, append) {
  206. // #ifdef APP-PLUS-NVUE
  207. if (!html)
  208. return this.height = 1;
  209. if (append)
  210. this.$refs.web.evalJs("var b=document.createElement('div');b.innerHTML='" + html.replace(/'/g, "\\'") +
  211. "';document.getElementById('parser').appendChild(b)");
  212. else {
  213. html =
  214. '<meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><style>html,body{width:100%;height:100%;overflow:hidden}body{margin:0}</style><base href="' +
  215. this.domain + '"><div id="parser"' + (this.selectable ? '>' : ' style="user-select:none">') + this._handleHtml(html).replace(/\n/g, '\\n') +
  216. '</div><script>"use strict";function e(e){if(window.__dcloud_weex_postMessage||window.__dcloud_weex_){var t={data:[e]};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(t):window.__dcloud_weex_.postMessage(JSON.stringify(t))}}document.body.onclick=function(){e({action:"click"})},' +
  217. (this.showWithAnimation ? 'document.body.style.animation="_show .5s",' : '') +
  218. 'setTimeout(function(){e({action:"load",text:document.body.innerText,height:document.getElementById("parser").scrollHeight})},50);\x3c/script>';
  219. this.$refs.web.evalJs("document.write('" + html.replace(/'/g, "\\'") + "');document.close()");
  220. }
  221. this.$refs.web.evalJs(
  222. 'var t=document.getElementsByTagName("title");t.length&&e({action:"getTitle",title:t[0].innerText});for(var o,n=document.getElementsByTagName("style"),r=1;o=n[r++];)o.innerHTML=o.innerHTML.replace(/body/g,"#parser");for(var a,c=document.getElementsByTagName("img"),s=[],i=0==c.length,d=0,l=0,g=0;a=c[l];l++)parseInt(a.style.width||a.getAttribute("width"))>' +
  223. windowWidth + '&&(a.style.height="auto"),a.onload=function(){++d==c.length&&(i=!0)},a.onerror=function(){++d==c.length&&(i=!0),' + (cfg.errorImg ? 'this.src="' + cfg.errorImg + '",' : '') +
  224. 'e({action:"error",source:"img",target:this})},a.hasAttribute("ignore")||"A"==a.parentElement.nodeName||(a.i=g++,s.push(a.src),a.onclick=function(){e({action:"preview",img:{i:this.i,src:this.src}})});e({action:"getImgList",imgList:s});for(var u,m=document.getElementsByTagName("a"),f=0;u=m[f];f++)u.onclick=function(){var t,o=this.getAttribute("href");if("#"==o[0]){var n=document.getElementById(o.substr(1));n&&(t=n.offsetTop)}return e({action:"linkpress",href:o,offset:t}),!1};for(var h,y=document.getElementsByTagName("video"),v=0;h=y[v];v++)h.style.maxWidth="100%",h.onerror=function(){e({action:"error",source:"video",target:this})}' +
  225. (this.autopause ? ',h.onplay=function(){for(var e,t=0;e=y[t];t++)e!=this&&e.pause()}' : '') +
  226. ';for(var _,p=document.getElementsByTagName("audio"),w=0;_=p[w];w++)_.onerror=function(){e({action:"error",source:"audio",target:this})};' +
  227. (this.autoscroll ? 'for(var T,E=document.getElementsByTagName("table"),B=0;T=E[B];B++){var N=document.createElement("div");N.style.overflow="scroll",T.parentNode.replaceChild(N,T),N.appendChild(T)}' : '') +
  228. 'var x=document.getElementById("parser");clearInterval(window.timer),window.timer=setInterval(function(){i&&clearInterval(window.timer),e({action:"ready",ready:i,height:x.scrollHeight})},350)'
  229. )
  230. this.nodes = [1];
  231. // #endif
  232. // #ifdef H5 || MP-360
  233. if (!html) {
  234. if (this.rtf && !append) this.rtf.parentNode.removeChild(this.rtf);
  235. return;
  236. }
  237. var div = document.createElement('div');
  238. if (!append) {
  239. if (this.rtf) this.rtf.parentNode.removeChild(this.rtf);
  240. this.rtf = div;
  241. } else {
  242. if (!this.rtf) this.rtf = div;
  243. else this.rtf.appendChild(div);
  244. }
  245. div.innerHTML = this._handleHtml(html, append);
  246. for (var styles = this.rtf.getElementsByTagName('style'), i = 0, style; style = styles[i++];) {
  247. style.innerHTML = style.innerHTML.replace(/body/g, '#rtf' + this._uid);
  248. style.setAttribute('scoped', 'true');
  249. }
  250. // 懒加载
  251. if (!this._observer && this.lazyLoad && IntersectionObserver) {
  252. this._observer = new IntersectionObserver(changes => {
  253. for (let item, i = 0; item = changes[i++];) {
  254. if (item.isIntersecting) {
  255. item.target.src = item.target.getAttribute('data-src');
  256. item.target.removeAttribute('data-src');
  257. this._observer.unobserve(item.target);
  258. }
  259. }
  260. }, {
  261. rootMargin: '500px 0px 500px 0px'
  262. })
  263. }
  264. var _ts = this;
  265. // 获取标题
  266. var title = this.rtf.getElementsByTagName('title');
  267. if (title.length && this.autosetTitle)
  268. uni.setNavigationBarTitle({
  269. title: title[0].innerText
  270. })
  271. // 图片处理
  272. this.imgList.length = 0;
  273. var imgs = this.rtf.getElementsByTagName('img');
  274. for (let i = 0, j = 0, img; img = imgs[i]; i++) {
  275. if (parseInt(img.style.width || img.getAttribute('width')) > windowWidth)
  276. img.style.height = 'auto';
  277. var src = img.getAttribute('src');
  278. if (this.domain && src) {
  279. if (src[0] == '/') {
  280. if (src[1] == '/')
  281. img.src = (this.domain.includes('://') ? this.domain.split('://')[0] : '') + ':' + src;
  282. else img.src = this.domain + src;
  283. } else if (!src.includes('://')) img.src = this.domain + '/' + src;
  284. }
  285. if (!img.hasAttribute('ignore') && img.parentElement.nodeName != 'A') {
  286. img.i = j++;
  287. _ts.imgList.push(img.src || img.getAttribute('data-src'));
  288. img.onclick = function() {
  289. var preview = true;
  290. this.ignore = () => preview = false;
  291. _ts.$emit('imgtap', this);
  292. if (preview) {
  293. uni.previewImage({
  294. current: this.i,
  295. urls: _ts.imgList
  296. });
  297. }
  298. }
  299. }
  300. img.onerror = function() {
  301. if (cfg.errorImg)
  302. _ts.imgList[this.i] = this.src = cfg.errorImg;
  303. _ts.$emit('error', {
  304. source: 'img',
  305. target: this
  306. });
  307. }
  308. if (_ts.lazyLoad && this._observer && img.src && img.i != 0) {
  309. img.setAttribute('data-src', img.src);
  310. img.removeAttribute('src');
  311. this._observer.observe(img);
  312. }
  313. }
  314. // 链接处理
  315. var links = this.rtf.getElementsByTagName('a');
  316. for (var link of links) {
  317. link.onclick = function() {
  318. var jump = true,
  319. href = this.getAttribute('href');
  320. _ts.$emit('linkpress', {
  321. href,
  322. ignore: () => jump = false
  323. });
  324. if (jump && href) {
  325. if (href[0] == '#') {
  326. if (_ts.useAnchor) {
  327. _ts.navigateTo({
  328. id: href.substr(1)
  329. })
  330. }
  331. } else if (href.indexOf('http') == 0 || href.indexOf('//') == 0)
  332. return true;
  333. else
  334. uni.navigateTo({
  335. url: href
  336. })
  337. }
  338. return false;
  339. }
  340. }
  341. // 视频处理
  342. var videos = this.rtf.getElementsByTagName('video');
  343. _ts.videoContexts = videos;
  344. for (let video, i = 0; video = videos[i++];) {
  345. video.style.maxWidth = '100%';
  346. video.onerror = function() {
  347. _ts.$emit('error', {
  348. source: 'video',
  349. target: this
  350. });
  351. }
  352. video.onplay = function() {
  353. if (_ts.autopause)
  354. for (let item, i = 0; item = _ts.videoContexts[i++];)
  355. if (item != this) item.pause();
  356. }
  357. }
  358. // 音频处理
  359. var audios = this.rtf.getElementsByTagName('audio');
  360. for (var audio of audios)
  361. audio.onerror = function() {
  362. _ts.$emit('error', {
  363. source: 'audio',
  364. target: this
  365. });
  366. }
  367. // 表格处理
  368. if (this.autoscroll) {
  369. var tables = this.rtf.getElementsByTagName('table');
  370. for (var table of tables) {
  371. let div = document.createElement('div');
  372. div.style.overflow = 'scroll';
  373. table.parentNode.replaceChild(div, table);
  374. div.appendChild(table);
  375. }
  376. }
  377. if (!append) this.document.appendChild(this.rtf);
  378. this.$nextTick(() => {
  379. this.nodes = [1];
  380. this.$emit('load');
  381. });
  382. setTimeout(() => this.showAm = '', 500);
  383. // #endif
  384. // #ifndef APP-PLUS-NVUE
  385. // #ifndef H5 || MP-360
  386. var nodes;
  387. if (!html) return this.nodes = [];
  388. var parser = new Parser(html, this);
  389. // 缓存读取
  390. if (this.useCache) {
  391. var hashVal = hash(html);
  392. if (cache[hashVal])
  393. nodes = cache[hashVal];
  394. else {
  395. nodes = parser.parse();
  396. cache[hashVal] = nodes;
  397. }
  398. } else nodes = parser.parse();
  399. this.$emit('parse', nodes);
  400. if (append) this.nodes = this.nodes.concat(nodes);
  401. else this.nodes = nodes;
  402. if (nodes.length && nodes.title && this.autosetTitle)
  403. uni.setNavigationBarTitle({
  404. title: nodes.title
  405. })
  406. if (this.imgList) this.imgList.length = 0;
  407. this.videoContexts = [];
  408. this.$nextTick(() => {
  409. (function f(cs) {
  410. for (var i = cs.length; i--;) {
  411. if (cs[i].top) {
  412. cs[i].controls = [];
  413. cs[i].init();
  414. f(cs[i].$children);
  415. }
  416. }
  417. })(this.$children)
  418. this.$emit('load');
  419. })
  420. // #endif
  421. var height;
  422. clearInterval(this._timer);
  423. this._timer = setInterval(() => {
  424. // #ifdef H5 || MP-360
  425. this.rect = this.rtf.getBoundingClientRect();
  426. // #endif
  427. // #ifndef H5 || MP-360
  428. uni.createSelectorQuery().in(this)
  429. .select('#_top').boundingClientRect().exec(res => {
  430. if (!res) return;
  431. this.rect = res[0];
  432. // #endif
  433. if (this.rect.height == height) {
  434. this.$emit('ready', this.rect)
  435. clearInterval(this._timer);
  436. }
  437. height = this.rect.height;
  438. // #ifndef H5 || MP-360
  439. });
  440. // #endif
  441. }, 350);
  442. if (this.showWithAnimation && !append) this.showAm = 'animation:_show .5s';
  443. // #endif
  444. },
  445. // 获取文本内容
  446. getText(ns = this.nodes) {
  447. var txt = '';
  448. // #ifdef APP-PLUS-NVUE
  449. txt = this._text;
  450. // #endif
  451. // #ifdef H5 || MP-360
  452. txt = this.rtf.innerText;
  453. // #endif
  454. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  455. for (var i = 0, n; n = ns[i++];) {
  456. if (n.type == 'text') txt += n.text.replace(/&nbsp;/g, '\u00A0').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  457. .replace(/&amp;/g, '&');
  458. else if (n.type == 'br') txt += '\n';
  459. else {
  460. // 块级标签前后加换行
  461. var block = n.name == 'p' || n.name == 'div' || n.name == 'tr' || n.name == 'li' || (n.name[0] == 'h' && n.name[1] >
  462. '0' && n.name[1] < '7');
  463. if (block && txt && txt[txt.length - 1] != '\n') txt += '\n';
  464. if (n.children) txt += this.getText(n.children);
  465. if (block && txt[txt.length - 1] != '\n') txt += '\n';
  466. else if (n.name == 'td' || n.name == 'th') txt += '\t';
  467. }
  468. }
  469. // #endif
  470. return txt;
  471. },
  472. // 锚点跳转
  473. in (obj) {
  474. if (obj.page && obj.selector && obj.scrollTop) this._in = obj;
  475. },
  476. navigateTo(obj) {
  477. if (!this.useAnchor) return obj.fail && obj.fail('Anchor is disabled');
  478. // #ifdef APP-PLUS-NVUE
  479. if (!obj.id)
  480. weexDom.scrollToElement(this.$refs.web);
  481. else
  482. this.$refs.web.evalJs('var pos=document.getElementById("' + obj.id +
  483. '");if(pos)post({action:"linkpress",href:"#",offset:pos.offsetTop+' + (obj.offset || 0) + '})');
  484. obj.success && obj.success();
  485. // #endif
  486. // #ifndef APP-PLUS-NVUE
  487. var d = ' ';
  488. // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
  489. d = '>>>';
  490. // #endif
  491. var selector = uni.createSelectorQuery().in(this._in ? this._in.page : this).select((this._in ? this._in.selector :
  492. '#_top') + (obj.id ? `${d}#${obj.id},${this._in?this._in.selector:'#_top'}${d}.${obj.id}` : '')).boundingClientRect();
  493. if (this._in) selector.select(this._in.selector).scrollOffset().select(this._in.selector).boundingClientRect();
  494. else selector.selectViewport().scrollOffset();
  495. selector.exec(res => {
  496. if (!res[0]) return obj.fail && obj.fail('Label not found')
  497. var scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + (obj.offset || 0);
  498. if (this._in) this._in.page[this._in.scrollTop] = scrollTop;
  499. else uni.pageScrollTo({
  500. scrollTop,
  501. duration: 300
  502. })
  503. obj.success && obj.success();
  504. })
  505. // #endif
  506. },
  507. // 获取视频对象
  508. getVideoContext(id) {
  509. // #ifndef APP-PLUS-NVUE
  510. if (!id) return this.videoContexts;
  511. else
  512. for (var i = this.videoContexts.length; i--;)
  513. if (this.videoContexts[i].id == id) return this.videoContexts[i];
  514. // #endif
  515. },
  516. // #ifdef H5 || APP-PLUS-NVUE || MP-360
  517. _handleHtml(html, append) {
  518. if (!append) {
  519. // 处理 tag-style 和 userAgentStyles
  520. var style = '<style>@keyframes _show{0%{opacity:0}100%{opacity:1}}img{max-width:100%}';
  521. for (var item in cfg.userAgentStyles)
  522. style += `${item}{${cfg.userAgentStyles[item]}}`;
  523. for (item in this.tagStyle)
  524. style += `${item}{${this.tagStyle[item]}}`;
  525. style += '</style>';
  526. html = style + html;
  527. }
  528. // 处理 rpx
  529. if (html.includes('rpx'))
  530. html = html.replace(/[0-9.]+\s*rpx/g, $ => (parseFloat($) * windowWidth / 750) + 'px');
  531. return html;
  532. },
  533. // #endif
  534. // #ifdef APP-PLUS-NVUE
  535. _message(e) {
  536. // 接收 web-view 消息
  537. var d = e.detail.data[0];
  538. switch (d.action) {
  539. case 'load':
  540. this.$emit('load');
  541. this.height = d.height;
  542. this._text = d.text;
  543. break;
  544. case 'getTitle':
  545. if (this.autosetTitle)
  546. uni.setNavigationBarTitle({
  547. title: d.title
  548. })
  549. break;
  550. case 'getImgList':
  551. this.imgList.length = 0;
  552. for (var i = d.imgList.length; i--;)
  553. this.imgList.setItem(i, d.imgList[i]);
  554. break;
  555. case 'preview':
  556. var preview = true;
  557. d.img.ignore = () => preview = false;
  558. this.$emit('imgtap', d.img);
  559. if (preview)
  560. uni.previewImage({
  561. current: d.img.i,
  562. urls: this.imgList
  563. })
  564. break;
  565. case 'linkpress':
  566. var jump = true,
  567. href = d.href;
  568. this.$emit('linkpress', {
  569. href,
  570. ignore: () => jump = false
  571. })
  572. if (jump && href) {
  573. if (href[0] == '#') {
  574. if (this.useAnchor)
  575. weexDom.scrollToElement(this.$refs.web, {
  576. offset: d.offset
  577. })
  578. } else if (href.includes('://'))
  579. plus.runtime.openWeb(href);
  580. else
  581. uni.navigateTo({
  582. url: href
  583. })
  584. }
  585. break;
  586. case 'error':
  587. if (d.source == 'img' && cfg.errorImg)
  588. this.imgList.setItem(d.target.i, cfg.errorImg);
  589. this.$emit('error', {
  590. source: d.source,
  591. target: d.target
  592. })
  593. break;
  594. case 'ready':
  595. this.height = d.height;
  596. if (d.ready) uni.createSelectorQuery().in(this).select('#_top').boundingClientRect().exec(res => {
  597. this.rect = res[0];
  598. this.$emit('ready', res[0]);
  599. })
  600. break;
  601. case 'click':
  602. this.$emit('click');
  603. this.$emit('tap');
  604. }
  605. },
  606. // #endif
  607. }
  608. }
  609. </script>
  610. <style>
  611. @keyframes _show {
  612. 0% {
  613. opacity: 0;
  614. }
  615. 100% {
  616. opacity: 1;
  617. }
  618. }
  619. /* #ifdef MP-WEIXIN */
  620. :host {
  621. display: block;
  622. overflow: scroll;
  623. -webkit-overflow-scrolling: touch;
  624. }
  625. /* #endif */
  626. =======
  627. <template>
  628. <view>
  629. <slot v-if="!nodes.length" />
  630. <!--#ifdef APP-PLUS-NVUE-->
  631. <web-view id="_top" ref="web" :style="'margin-top:-2px;height:'+height+'px'" @onPostMessage="_message" />
  632. <!--#endif-->
  633. <!--#ifndef APP-PLUS-NVUE-->
  634. <view id="_top" :style="showAm+(selectable?';user-select:text;-webkit-user-select:text':'')">
  635. <!--#ifdef H5 || MP-360-->
  636. <div :id="'rtf'+uid"></div>
  637. <!--#endif-->
  638. <!--#ifndef H5 || MP-360-->
  639. <trees :nodes="nodes" :lazyLoad="lazyLoad" :loading="loadingImg" />
  640. <!--#endif-->
  641. </view>
  642. <!--#endif-->
  643. </view>
  644. </template>
  645. <script>
  646. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  647. import trees from './libs/trees';
  648. var cache = {},
  649. // #ifdef MP-WEIXIN || MP-TOUTIAO
  650. fs = uni.getFileSystemManager ? uni.getFileSystemManager() : null,
  651. // #endif
  652. Parser = require('./libs/MpHtmlParser.js');
  653. var dom;
  654. // 计算 cache 的 key
  655. function hash(str) {
  656. for (var i = str.length, val = 5381; i--;)
  657. val += (val << 5) + str.charCodeAt(i);
  658. return val;
  659. }
  660. // #endif
  661. // #ifdef H5 || APP-PLUS-NVUE || MP-360
  662. var windowWidth = uni.getSystemInfoSync().windowWidth,
  663. cfg = require('./libs/config.js');
  664. // #endif
  665. // #ifdef APP-PLUS-NVUE
  666. var weexDom = weex.requireModule('dom');
  667. // #endif
  668. /**
  669. * Parser 富文本组件
  670. * @tutorial https://github.com/jin-yufeng/Parser
  671. * @property {String} html 富文本数据
  672. * @property {Boolean} autopause 是否在播放一个视频时自动暂停其他视频
  673. * @property {Boolean} autoscroll 是否自动给所有表格添加一个滚动层
  674. * @property {Boolean} autosetTitle 是否自动将 title 标签中的内容设置到页面标题
  675. * @property {Number} compress 压缩等级
  676. * @property {String} domain 图片、视频等链接的主域名
  677. * @property {Boolean} lazyLoad 是否开启图片懒加载
  678. * @property {String} loadingImg 图片加载完成前的占位图
  679. * @property {Boolean} selectable 是否开启长按复制
  680. * @property {Object} tagStyle 标签的默认样式
  681. * @property {Boolean} showWithAnimation 是否使用渐显动画
  682. * @property {Boolean} useAnchor 是否使用锚点
  683. * @property {Boolean} useCache 是否缓存解析结果
  684. * @event {Function} parse 解析完成事件
  685. * @event {Function} load dom 加载完成事件
  686. * @event {Function} ready 所有图片加载完毕事件
  687. * @event {Function} error 错误事件
  688. * @event {Function} imgtap 图片点击事件
  689. * @event {Function} linkpress 链接点击事件
  690. * @author JinYufeng
  691. * @version 20200728
  692. * @listens MIT
  693. */
  694. export default {
  695. name: 'parser',
  696. data() {
  697. return {
  698. // #ifdef H5 || MP-360
  699. uid: this._uid,
  700. // #endif
  701. // #ifdef APP-PLUS-NVUE
  702. height: 1,
  703. // #endif
  704. // #ifndef APP-PLUS-NVUE
  705. showAm: '',
  706. // #endif
  707. nodes: []
  708. }
  709. },
  710. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  711. components: {
  712. trees
  713. },
  714. // #endif
  715. props: {
  716. html: String,
  717. autopause: {
  718. type: Boolean,
  719. default: true
  720. },
  721. autoscroll: Boolean,
  722. autosetTitle: {
  723. type: Boolean,
  724. default: true
  725. },
  726. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  727. compress: Number,
  728. loadingImg: String,
  729. useCache: Boolean,
  730. // #endif
  731. domain: String,
  732. lazyLoad: Boolean,
  733. selectable: Boolean,
  734. tagStyle: Object,
  735. showWithAnimation: Boolean,
  736. useAnchor: Boolean
  737. },
  738. watch: {
  739. html(html) {
  740. this.setContent(html);
  741. }
  742. },
  743. created() {
  744. // 图片数组
  745. this.imgList = [];
  746. this.imgList.each = function(f) {
  747. for (var i = 0, len = this.length; i < len; i++)
  748. this.setItem(i, f(this[i], i, this));
  749. }
  750. this.imgList.setItem = function(i, src) {
  751. if (i == void 0 || !src) return;
  752. // #ifndef MP-ALIPAY || APP-PLUS
  753. // 去重
  754. if (src.indexOf('http') == 0 && this.includes(src)) {
  755. var newSrc = src.split('://')[0];
  756. for (var j = newSrc.length, c; c = src[j]; j++) {
  757. if (c == '/' && src[j - 1] != '/' && src[j + 1] != '/') break;
  758. newSrc += Math.random() > 0.5 ? c.toUpperCase() : c;
  759. }
  760. newSrc += src.substr(j);
  761. return this[i] = newSrc;
  762. }
  763. // #endif
  764. this[i] = src;
  765. // 暂存 data src
  766. if (src.includes('data:image')) {
  767. var filePath, info = src.match(/data:image\/(\S+?);(\S+?),(.+)/);
  768. if (!info) return;
  769. // #ifdef MP-WEIXIN || MP-TOUTIAO
  770. filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.${info[1]}`;
  771. fs && fs.writeFile({
  772. filePath,
  773. data: info[3],
  774. encoding: info[2],
  775. success: () => this[i] = filePath
  776. })
  777. // #endif
  778. // #ifdef APP-PLUS
  779. filePath = `_doc/parser_tmp/${Date.now()}.${info[1]}`;
  780. var bitmap = new plus.nativeObj.Bitmap();
  781. bitmap.loadBase64Data(src, () => {
  782. bitmap.save(filePath, {}, () => {
  783. bitmap.clear()
  784. this[i] = filePath;
  785. })
  786. })
  787. // #endif
  788. }
  789. }
  790. },
  791. mounted() {
  792. // #ifdef H5 || MP-360
  793. this.document = document.getElementById('rtf' + this._uid);
  794. // #endif
  795. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  796. if (dom) this.document = new dom(this);
  797. // #endif
  798. // #ifdef APP-PLUS-NVUE
  799. this.document = this.$refs.web;
  800. setTimeout(() => {
  801. // #endif
  802. if (this.html) this.setContent(this.html);
  803. // #ifdef APP-PLUS-NVUE
  804. }, 30)
  805. // #endif
  806. },
  807. beforeDestroy() {
  808. // #ifdef H5 || MP-360
  809. if (this._observer) this._observer.disconnect();
  810. // #endif
  811. this.imgList.each(src => {
  812. // #ifdef APP-PLUS
  813. if (src && src.includes('_doc')) {
  814. plus.io.resolveLocalFileSystemURL(src, entry => {
  815. entry.remove();
  816. });
  817. }
  818. // #endif
  819. // #ifdef MP-WEIXIN || MP-TOUTIAO
  820. if (src && src.includes(uni.env.USER_DATA_PATH))
  821. fs && fs.unlink({
  822. filePath: src
  823. })
  824. // #endif
  825. })
  826. clearInterval(this._timer);
  827. },
  828. methods: {
  829. // 设置富文本内容
  830. setContent(html, append) {
  831. // #ifdef APP-PLUS-NVUE
  832. if (!html)
  833. return this.height = 1;
  834. if (append)
  835. this.$refs.web.evalJs("var b=document.createElement('div');b.innerHTML='" + html.replace(/'/g, "\\'") +
  836. "';document.getElementById('parser').appendChild(b)");
  837. else {
  838. html =
  839. '<meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><style>html,body{width:100%;height:100%;overflow:hidden}body{margin:0}</style><base href="' +
  840. this.domain + '"><div id="parser"' + (this.selectable ? '>' : ' style="user-select:none">') + this._handleHtml(html).replace(/\n/g, '\\n') +
  841. '</div><script>"use strict";function e(e){if(window.__dcloud_weex_postMessage||window.__dcloud_weex_){var t={data:[e]};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(t):window.__dcloud_weex_.postMessage(JSON.stringify(t))}}document.body.onclick=function(){e({action:"click"})},' +
  842. (this.showWithAnimation ? 'document.body.style.animation="_show .5s",' : '') +
  843. 'setTimeout(function(){e({action:"load",text:document.body.innerText,height:document.getElementById("parser").scrollHeight})},50);\x3c/script>';
  844. this.$refs.web.evalJs("document.write('" + html.replace(/'/g, "\\'") + "');document.close()");
  845. }
  846. this.$refs.web.evalJs(
  847. 'var t=document.getElementsByTagName("title");t.length&&e({action:"getTitle",title:t[0].innerText});for(var o,n=document.getElementsByTagName("style"),r=1;o=n[r++];)o.innerHTML=o.innerHTML.replace(/body/g,"#parser");for(var a,c=document.getElementsByTagName("img"),s=[],i=0==c.length,d=0,l=0,g=0;a=c[l];l++)parseInt(a.style.width||a.getAttribute("width"))>' +
  848. windowWidth + '&&(a.style.height="auto"),a.onload=function(){++d==c.length&&(i=!0)},a.onerror=function(){++d==c.length&&(i=!0),' + (cfg.errorImg ? 'this.src="' + cfg.errorImg + '",' : '') +
  849. 'e({action:"error",source:"img",target:this})},a.hasAttribute("ignore")||"A"==a.parentElement.nodeName||(a.i=g++,s.push(a.src),a.onclick=function(){e({action:"preview",img:{i:this.i,src:this.src}})});e({action:"getImgList",imgList:s});for(var u,m=document.getElementsByTagName("a"),f=0;u=m[f];f++)u.onclick=function(){var t,o=this.getAttribute("href");if("#"==o[0]){var n=document.getElementById(o.substr(1));n&&(t=n.offsetTop)}return e({action:"linkpress",href:o,offset:t}),!1};for(var h,y=document.getElementsByTagName("video"),v=0;h=y[v];v++)h.style.maxWidth="100%",h.onerror=function(){e({action:"error",source:"video",target:this})}' +
  850. (this.autopause ? ',h.onplay=function(){for(var e,t=0;e=y[t];t++)e!=this&&e.pause()}' : '') +
  851. ';for(var _,p=document.getElementsByTagName("audio"),w=0;_=p[w];w++)_.onerror=function(){e({action:"error",source:"audio",target:this})};' +
  852. (this.autoscroll ? 'for(var T,E=document.getElementsByTagName("table"),B=0;T=E[B];B++){var N=document.createElement("div");N.style.overflow="scroll",T.parentNode.replaceChild(N,T),N.appendChild(T)}' : '') +
  853. 'var x=document.getElementById("parser");clearInterval(window.timer),window.timer=setInterval(function(){i&&clearInterval(window.timer),e({action:"ready",ready:i,height:x.scrollHeight})},350)'
  854. )
  855. this.nodes = [1];
  856. // #endif
  857. // #ifdef H5 || MP-360
  858. if (!html) {
  859. if (this.rtf && !append) this.rtf.parentNode.removeChild(this.rtf);
  860. return;
  861. }
  862. var div = document.createElement('div');
  863. if (!append) {
  864. if (this.rtf) this.rtf.parentNode.removeChild(this.rtf);
  865. this.rtf = div;
  866. } else {
  867. if (!this.rtf) this.rtf = div;
  868. else this.rtf.appendChild(div);
  869. }
  870. div.innerHTML = this._handleHtml(html, append);
  871. for (var styles = this.rtf.getElementsByTagName('style'), i = 0, style; style = styles[i++];) {
  872. style.innerHTML = style.innerHTML.replace(/body/g, '#rtf' + this._uid);
  873. style.setAttribute('scoped', 'true');
  874. }
  875. // 懒加载
  876. if (!this._observer && this.lazyLoad && IntersectionObserver) {
  877. this._observer = new IntersectionObserver(changes => {
  878. for (let item, i = 0; item = changes[i++];) {
  879. if (item.isIntersecting) {
  880. item.target.src = item.target.getAttribute('data-src');
  881. item.target.removeAttribute('data-src');
  882. this._observer.unobserve(item.target);
  883. }
  884. }
  885. }, {
  886. rootMargin: '500px 0px 500px 0px'
  887. })
  888. }
  889. var _ts = this;
  890. // 获取标题
  891. var title = this.rtf.getElementsByTagName('title');
  892. if (title.length && this.autosetTitle)
  893. uni.setNavigationBarTitle({
  894. title: title[0].innerText
  895. })
  896. // 图片处理
  897. this.imgList.length = 0;
  898. var imgs = this.rtf.getElementsByTagName('img');
  899. for (let i = 0, j = 0, img; img = imgs[i]; i++) {
  900. if (parseInt(img.style.width || img.getAttribute('width')) > windowWidth)
  901. img.style.height = 'auto';
  902. var src = img.getAttribute('src');
  903. if (this.domain && src) {
  904. if (src[0] == '/') {
  905. if (src[1] == '/')
  906. img.src = (this.domain.includes('://') ? this.domain.split('://')[0] : '') + ':' + src;
  907. else img.src = this.domain + src;
  908. } else if (!src.includes('://')) img.src = this.domain + '/' + src;
  909. }
  910. if (!img.hasAttribute('ignore') && img.parentElement.nodeName != 'A') {
  911. img.i = j++;
  912. _ts.imgList.push(img.src || img.getAttribute('data-src'));
  913. img.onclick = function() {
  914. var preview = true;
  915. this.ignore = () => preview = false;
  916. _ts.$emit('imgtap', this);
  917. if (preview) {
  918. uni.previewImage({
  919. current: this.i,
  920. urls: _ts.imgList
  921. });
  922. }
  923. }
  924. }
  925. img.onerror = function() {
  926. if (cfg.errorImg)
  927. _ts.imgList[this.i] = this.src = cfg.errorImg;
  928. _ts.$emit('error', {
  929. source: 'img',
  930. target: this
  931. });
  932. }
  933. if (_ts.lazyLoad && this._observer && img.src && img.i != 0) {
  934. img.setAttribute('data-src', img.src);
  935. img.removeAttribute('src');
  936. this._observer.observe(img);
  937. }
  938. }
  939. // 链接处理
  940. var links = this.rtf.getElementsByTagName('a');
  941. for (var link of links) {
  942. link.onclick = function() {
  943. var jump = true,
  944. href = this.getAttribute('href');
  945. _ts.$emit('linkpress', {
  946. href,
  947. ignore: () => jump = false
  948. });
  949. if (jump && href) {
  950. if (href[0] == '#') {
  951. if (_ts.useAnchor) {
  952. _ts.navigateTo({
  953. id: href.substr(1)
  954. })
  955. }
  956. } else if (href.indexOf('http') == 0 || href.indexOf('//') == 0)
  957. return true;
  958. else
  959. uni.navigateTo({
  960. url: href
  961. })
  962. }
  963. return false;
  964. }
  965. }
  966. // 视频处理
  967. var videos = this.rtf.getElementsByTagName('video');
  968. _ts.videoContexts = videos;
  969. for (let video, i = 0; video = videos[i++];) {
  970. video.style.maxWidth = '100%';
  971. video.onerror = function() {
  972. _ts.$emit('error', {
  973. source: 'video',
  974. target: this
  975. });
  976. }
  977. video.onplay = function() {
  978. if (_ts.autopause)
  979. for (let item, i = 0; item = _ts.videoContexts[i++];)
  980. if (item != this) item.pause();
  981. }
  982. }
  983. // 音频处理
  984. var audios = this.rtf.getElementsByTagName('audio');
  985. for (var audio of audios)
  986. audio.onerror = function() {
  987. _ts.$emit('error', {
  988. source: 'audio',
  989. target: this
  990. });
  991. }
  992. // 表格处理
  993. if (this.autoscroll) {
  994. var tables = this.rtf.getElementsByTagName('table');
  995. for (var table of tables) {
  996. let div = document.createElement('div');
  997. div.style.overflow = 'scroll';
  998. table.parentNode.replaceChild(div, table);
  999. div.appendChild(table);
  1000. }
  1001. }
  1002. if (!append) this.document.appendChild(this.rtf);
  1003. this.$nextTick(() => {
  1004. this.nodes = [1];
  1005. this.$emit('load');
  1006. });
  1007. setTimeout(() => this.showAm = '', 500);
  1008. // #endif
  1009. // #ifndef APP-PLUS-NVUE
  1010. // #ifndef H5 || MP-360
  1011. var nodes;
  1012. if (!html) return this.nodes = [];
  1013. var parser = new Parser(html, this);
  1014. // 缓存读取
  1015. if (this.useCache) {
  1016. var hashVal = hash(html);
  1017. if (cache[hashVal])
  1018. nodes = cache[hashVal];
  1019. else {
  1020. nodes = parser.parse();
  1021. cache[hashVal] = nodes;
  1022. }
  1023. } else nodes = parser.parse();
  1024. this.$emit('parse', nodes);
  1025. if (append) this.nodes = this.nodes.concat(nodes);
  1026. else this.nodes = nodes;
  1027. if (nodes.length && nodes.title && this.autosetTitle)
  1028. uni.setNavigationBarTitle({
  1029. title: nodes.title
  1030. })
  1031. if (this.imgList) this.imgList.length = 0;
  1032. this.videoContexts = [];
  1033. this.$nextTick(() => {
  1034. (function f(cs) {
  1035. for (var i = cs.length; i--;) {
  1036. if (cs[i].top) {
  1037. cs[i].controls = [];
  1038. cs[i].init();
  1039. f(cs[i].$children);
  1040. }
  1041. }
  1042. })(this.$children)
  1043. this.$emit('load');
  1044. })
  1045. // #endif
  1046. var height;
  1047. clearInterval(this._timer);
  1048. this._timer = setInterval(() => {
  1049. // #ifdef H5 || MP-360
  1050. this.rect = this.rtf.getBoundingClientRect();
  1051. // #endif
  1052. // #ifndef H5 || MP-360
  1053. uni.createSelectorQuery().in(this)
  1054. .select('#_top').boundingClientRect().exec(res => {
  1055. if (!res) return;
  1056. this.rect = res[0];
  1057. // #endif
  1058. if (this.rect.height == height) {
  1059. this.$emit('ready', this.rect)
  1060. clearInterval(this._timer);
  1061. }
  1062. height = this.rect.height;
  1063. // #ifndef H5 || MP-360
  1064. });
  1065. // #endif
  1066. }, 350);
  1067. if (this.showWithAnimation && !append) this.showAm = 'animation:_show .5s';
  1068. // #endif
  1069. },
  1070. // 获取文本内容
  1071. getText(ns = this.nodes) {
  1072. var txt = '';
  1073. // #ifdef APP-PLUS-NVUE
  1074. txt = this._text;
  1075. // #endif
  1076. // #ifdef H5 || MP-360
  1077. txt = this.rtf.innerText;
  1078. // #endif
  1079. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  1080. for (var i = 0, n; n = ns[i++];) {
  1081. if (n.type == 'text') txt += n.text.replace(/&nbsp;/g, '\u00A0').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  1082. .replace(/&amp;/g, '&');
  1083. else if (n.type == 'br') txt += '\n';
  1084. else {
  1085. // 块级标签前后加换行
  1086. var block = n.name == 'p' || n.name == 'div' || n.name == 'tr' || n.name == 'li' || (n.name[0] == 'h' && n.name[1] >
  1087. '0' && n.name[1] < '7');
  1088. if (block && txt && txt[txt.length - 1] != '\n') txt += '\n';
  1089. if (n.children) txt += this.getText(n.children);
  1090. if (block && txt[txt.length - 1] != '\n') txt += '\n';
  1091. else if (n.name == 'td' || n.name == 'th') txt += '\t';
  1092. }
  1093. }
  1094. // #endif
  1095. return txt;
  1096. },
  1097. // 锚点跳转
  1098. in (obj) {
  1099. if (obj.page && obj.selector && obj.scrollTop) this._in = obj;
  1100. },
  1101. navigateTo(obj) {
  1102. if (!this.useAnchor) return obj.fail && obj.fail('Anchor is disabled');
  1103. // #ifdef APP-PLUS-NVUE
  1104. if (!obj.id)
  1105. weexDom.scrollToElement(this.$refs.web);
  1106. else
  1107. this.$refs.web.evalJs('var pos=document.getElementById("' + obj.id +
  1108. '");if(pos)post({action:"linkpress",href:"#",offset:pos.offsetTop+' + (obj.offset || 0) + '})');
  1109. obj.success && obj.success();
  1110. // #endif
  1111. // #ifndef APP-PLUS-NVUE
  1112. var d = ' ';
  1113. // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
  1114. d = '>>>';
  1115. // #endif
  1116. var selector = uni.createSelectorQuery().in(this._in ? this._in.page : this).select((this._in ? this._in.selector :
  1117. '#_top') + (obj.id ? `${d}#${obj.id},${this._in?this._in.selector:'#_top'}${d}.${obj.id}` : '')).boundingClientRect();
  1118. if (this._in) selector.select(this._in.selector).scrollOffset().select(this._in.selector).boundingClientRect();
  1119. else selector.selectViewport().scrollOffset();
  1120. selector.exec(res => {
  1121. if (!res[0]) return obj.fail && obj.fail('Label not found')
  1122. var scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + (obj.offset || 0);
  1123. if (this._in) this._in.page[this._in.scrollTop] = scrollTop;
  1124. else uni.pageScrollTo({
  1125. scrollTop,
  1126. duration: 300
  1127. })
  1128. obj.success && obj.success();
  1129. })
  1130. // #endif
  1131. },
  1132. // 获取视频对象
  1133. getVideoContext(id) {
  1134. // #ifndef APP-PLUS-NVUE
  1135. if (!id) return this.videoContexts;
  1136. else
  1137. for (var i = this.videoContexts.length; i--;)
  1138. if (this.videoContexts[i].id == id) return this.videoContexts[i];
  1139. // #endif
  1140. },
  1141. // #ifdef H5 || APP-PLUS-NVUE || MP-360
  1142. _handleHtml(html, append) {
  1143. if (!append) {
  1144. // 处理 tag-style 和 userAgentStyles
  1145. var style = '<style>@keyframes _show{0%{opacity:0}100%{opacity:1}}img{max-width:100%}';
  1146. for (var item in cfg.userAgentStyles)
  1147. style += `${item}{${cfg.userAgentStyles[item]}}`;
  1148. for (item in this.tagStyle)
  1149. style += `${item}{${this.tagStyle[item]}}`;
  1150. style += '</style>';
  1151. html = style + html;
  1152. }
  1153. // 处理 rpx
  1154. if (html.includes('rpx'))
  1155. html = html.replace(/[0-9.]+\s*rpx/g, $ => (parseFloat($) * windowWidth / 750) + 'px');
  1156. return html;
  1157. },
  1158. // #endif
  1159. // #ifdef APP-PLUS-NVUE
  1160. _message(e) {
  1161. // 接收 web-view 消息
  1162. var d = e.detail.data[0];
  1163. switch (d.action) {
  1164. case 'load':
  1165. this.$emit('load');
  1166. this.height = d.height;
  1167. this._text = d.text;
  1168. break;
  1169. case 'getTitle':
  1170. if (this.autosetTitle)
  1171. uni.setNavigationBarTitle({
  1172. title: d.title
  1173. })
  1174. break;
  1175. case 'getImgList':
  1176. this.imgList.length = 0;
  1177. for (var i = d.imgList.length; i--;)
  1178. this.imgList.setItem(i, d.imgList[i]);
  1179. break;
  1180. case 'preview':
  1181. var preview = true;
  1182. d.img.ignore = () => preview = false;
  1183. this.$emit('imgtap', d.img);
  1184. if (preview)
  1185. uni.previewImage({
  1186. current: d.img.i,
  1187. urls: this.imgList
  1188. })
  1189. break;
  1190. case 'linkpress':
  1191. var jump = true,
  1192. href = d.href;
  1193. this.$emit('linkpress', {
  1194. href,
  1195. ignore: () => jump = false
  1196. })
  1197. if (jump && href) {
  1198. if (href[0] == '#') {
  1199. if (this.useAnchor)
  1200. weexDom.scrollToElement(this.$refs.web, {
  1201. offset: d.offset
  1202. })
  1203. } else if (href.includes('://'))
  1204. plus.runtime.openWeb(href);
  1205. else
  1206. uni.navigateTo({
  1207. url: href
  1208. })
  1209. }
  1210. break;
  1211. case 'error':
  1212. if (d.source == 'img' && cfg.errorImg)
  1213. this.imgList.setItem(d.target.i, cfg.errorImg);
  1214. this.$emit('error', {
  1215. source: d.source,
  1216. target: d.target
  1217. })
  1218. break;
  1219. case 'ready':
  1220. this.height = d.height;
  1221. if (d.ready) uni.createSelectorQuery().in(this).select('#_top').boundingClientRect().exec(res => {
  1222. this.rect = res[0];
  1223. this.$emit('ready', res[0]);
  1224. })
  1225. break;
  1226. case 'click':
  1227. this.$emit('click');
  1228. this.$emit('tap');
  1229. }
  1230. },
  1231. // #endif
  1232. }
  1233. }
  1234. </script>
  1235. <style>
  1236. @keyframes _show {
  1237. 0% {
  1238. opacity: 0;
  1239. }
  1240. 100% {
  1241. opacity: 1;
  1242. }
  1243. }
  1244. /* #ifdef MP-WEIXIN */
  1245. :host {
  1246. display: block;
  1247. overflow: scroll;
  1248. -webkit-overflow-scrolling: touch;
  1249. }
  1250. /* #endif */
  1251. >>>>>>> 5b465a14bac2c1448cc18a0b08b88844fc895cd5
  1252. </style>