選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

u-parse.vue 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. <template>
  2. <view class="u-parse">
  3. <slot v-if="!nodes.length" />
  4. <!--#ifdef APP-PLUS-NVUE-->
  5. <web-view id="_top" ref="web" :style="'margin-top:-2px;height:'+height+'px'" @onPostMessage="_message" />
  6. <!--#endif-->
  7. <!--#ifndef APP-PLUS-NVUE-->
  8. <view id="_top" :style="showAm+(selectable?';user-select:text;-webkit-user-select:text':'')">
  9. <!--#ifdef H5 || MP-360-->
  10. <div :id="'rtf'+uid"></div>
  11. <!--#endif-->
  12. <!--#ifndef H5 || MP-360-->
  13. <trees :nodes="nodes" :lazyLoad="lazyLoad" :loading="loadingImg" :preview="preview"/>
  14. <!--#endif-->
  15. </view>
  16. <!--#endif-->
  17. </view>
  18. </template>
  19. <script>
  20. var search;
  21. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  22. import trees from './libs/trees';
  23. import Parser from './libs/MpHtmlParser.js'
  24. var cache = {};
  25. // #ifdef MP-WEIXIN || MP-TOUTIAO
  26. var fs = uni.getFileSystemManager ? uni.getFileSystemManager() : null;
  27. // #endif
  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. import cfg from './libs/config.js'
  38. var {
  39. windowWidth,
  40. platform
  41. } = uni.getSystemInfoSync()
  42. // #endif
  43. // #ifdef APP-PLUS-NVUE
  44. var weexDom = weex.requireModule('dom');
  45. // #endif
  46. /**
  47. * Parser 富文本组件
  48. * @tutorial https://github.com/jin-yufeng/Parser
  49. * @property {String} html 富文本数据
  50. * @property {Boolean} autopause 是否在播放一个视频时自动暂停其他视频
  51. * @property {Boolean} autoscroll 是否自动给所有表格添加一个滚动层
  52. * @property {Boolean} autosetTitle 是否自动将 title 标签中的内容设置到页面标题
  53. * @property {Number} compress 压缩等级
  54. * @property {String} domain 图片、视频等链接的主域名
  55. * @property {Boolean} lazyLoad 是否开启图片懒加载
  56. * @property {String} loadingImg 图片加载完成前的占位图
  57. * @property {Boolean} selectable 是否开启长按复制
  58. * @property {Object} tagStyle 标签的默认样式
  59. * @property {Boolean} showWithAnimation 是否使用渐显动画
  60. * @property {Boolean} useAnchor 是否使用锚点
  61. * @property {Boolean} useCache 是否缓存解析结果
  62. * @property {Boolean} preview 点击图片是否自动预览
  63. * @event {Function} parse 解析完成事件
  64. * @event {Function} load dom 加载完成事件
  65. * @event {Function} ready 所有图片加载完毕事件
  66. * @event {Function} error 错误事件
  67. * @event {Function} imgtap 图片点击事件
  68. * @event {Function} linkpress 链接点击事件
  69. * @author JinYufeng
  70. * @version 20201029
  71. * @listens MIT
  72. */
  73. export default {
  74. name: 'parser',
  75. emits: ["parse", "load", "ready", "error", "imgtap", "linkpress"],
  76. data() {
  77. return {
  78. // #ifdef H5 || MP-360
  79. uid: this._uid,
  80. // #endif
  81. // #ifdef APP-PLUS-NVUE
  82. height: 1,
  83. // #endif
  84. // #ifndef APP-PLUS-NVUE
  85. showAm: '',
  86. // #endif
  87. nodes: []
  88. }
  89. },
  90. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  91. components: {
  92. trees
  93. },
  94. // #endif
  95. props: {
  96. html: String,
  97. autopause: {
  98. type: Boolean,
  99. default: true
  100. },
  101. preview: {
  102. type: Boolean,
  103. default: true
  104. },
  105. autoscroll: Boolean,
  106. autosetTitle: {
  107. type: Boolean,
  108. default: true
  109. },
  110. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  111. compress: Number,
  112. loadingImg: String,
  113. useCache: Boolean,
  114. // #endif
  115. domain: String,
  116. lazyLoad: Boolean,
  117. selectable: Boolean,
  118. tagStyle: Object,
  119. showWithAnimation: Boolean,
  120. useAnchor: Boolean
  121. },
  122. watch: {
  123. html(html) {
  124. this.setContent(html);
  125. }
  126. },
  127. created() {
  128. // 图片数组
  129. this.imgList = [];
  130. this.imgList.each = function(f) {
  131. for (var i = 0, len = this.length; i < len; i++)
  132. this.setItem(i, f(this[i], i, this));
  133. }
  134. this.imgList.setItem = function(i, src) {
  135. if (i == void 0 || !src) return;
  136. // #ifndef MP-ALIPAY || APP-PLUS
  137. // 去重
  138. if (src.indexOf('http') == 0 && this.includes(src)) {
  139. var newSrc = src.split('://')[0];
  140. for (var j = newSrc.length, c; c = src[j]; j++) {
  141. if (c == '/' && src[j - 1] != '/' && src[j + 1] != '/') break;
  142. newSrc += Math.random() > 0.5 ? c.toUpperCase() : c;
  143. }
  144. newSrc += src.substr(j);
  145. return this[i] = newSrc;
  146. }
  147. // #endif
  148. this[i] = src;
  149. // 暂存 data src
  150. if (src.includes('data:image')) {
  151. var filePath, info = src.match(/data:image\/(\S+?);(\S+?),(.+)/);
  152. if (!info) return;
  153. // #ifdef MP-WEIXIN || MP-TOUTIAO
  154. filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.${info[1]}`;
  155. fs && fs.writeFile({
  156. filePath,
  157. data: info[3],
  158. encoding: info[2],
  159. success: () => this[i] = filePath
  160. })
  161. // #endif
  162. // #ifdef APP-PLUS
  163. filePath = `_doc/parser_tmp/${Date.now()}.${info[1]}`;
  164. var bitmap = new plus.nativeObj.Bitmap();
  165. bitmap.loadBase64Data(src, () => {
  166. bitmap.save(filePath, {}, () => {
  167. bitmap.clear()
  168. this[i] = filePath;
  169. })
  170. })
  171. // #endif
  172. }
  173. }
  174. },
  175. mounted() {
  176. // #ifdef H5 || MP-360
  177. this.document = document.getElementById('rtf' + this._uid);
  178. // #endif
  179. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  180. if (dom) this.document = new dom(this);
  181. // #endif
  182. if (search) this.search = args => search(this, args);
  183. // #ifdef APP-PLUS-NVUE
  184. this.document = this.$refs.web;
  185. setTimeout(() => {
  186. // #endif
  187. if (this.html) this.setContent(this.html);
  188. // #ifdef APP-PLUS-NVUE
  189. }, 30)
  190. // #endif
  191. },
  192. // #ifndef VUE3
  193. beforeDestroy() {
  194. // #ifdef H5 || MP-360
  195. if (this._observer) this._observer.disconnect();
  196. // #endif
  197. this.imgList.each(src => {
  198. // #ifdef APP-PLUS
  199. if (src && src.includes('_doc')) {
  200. plus.io.resolveLocalFileSystemURL(src, entry => {
  201. entry.remove();
  202. });
  203. }
  204. // #endif
  205. // #ifdef MP-WEIXIN || MP-TOUTIAO
  206. if (src && src.includes(uni.env.USER_DATA_PATH))
  207. fs && fs.unlink({
  208. filePath: src
  209. })
  210. // #endif
  211. })
  212. clearInterval(this._timer);
  213. },
  214. // #endif
  215. // #ifdef VUE3
  216. beforeUnmount() {
  217. // #ifdef H5 || MP-360
  218. if (this._observer) this._observer.disconnect();
  219. // #endif
  220. this.imgList.each(src => {
  221. // #ifdef APP-PLUS
  222. if (src && src.includes('_doc')) {
  223. plus.io.resolveLocalFileSystemURL(src, entry => {
  224. entry.remove();
  225. });
  226. }
  227. // #endif
  228. // #ifdef MP-WEIXIN || MP-TOUTIAO
  229. if (src && src.includes(uni.env.USER_DATA_PATH))
  230. fs && fs.unlink({
  231. filePath: src
  232. })
  233. // #endif
  234. })
  235. clearInterval(this._timer);
  236. },
  237. // #endif
  238. methods: {
  239. // 设置富文本内容
  240. setContent(html, append) {
  241. // #ifdef APP-PLUS-NVUE
  242. if (!html)
  243. return this.height = 1;
  244. if (append)
  245. this.$refs.web.evalJs("var b=document.createElement('div');b.innerHTML='" + html.replace(/'/g, "\\'") +
  246. "';document.getElementById('parser').appendChild(b)");
  247. else {
  248. html =
  249. '<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="' +
  250. this.domain + '"><div id="parser"' + (this.selectable ? '>' : ' style="user-select:none">') + this._handleHtml(html).replace(/\n/g, '\\n') +
  251. '</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"})},' +
  252. (this.showWithAnimation ? 'document.body.style.animation="_show .5s",' : '') +
  253. 'setTimeout(function(){e({action:"load",text:document.body.innerText,height:document.getElementById("parser").scrollHeight})},50);\x3c/script>';
  254. if (platform == 'android') html = html.replace(/%/g, '%25');
  255. this.$refs.web.evalJs("document.write('" + html.replace(/'/g, "\\'") + "');document.close()");
  256. }
  257. this.$refs.web.evalJs(
  258. '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"))>' +
  259. 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 + '",' : '') +
  260. 'e({action:"error",source:"img",target:this})},a.hasAttribute("ignore")||"A"==a.parentElement.nodeName||(a.i=g++,s.push(a.getAttribute("original-src")||a.src||a.getAttribute("data-src")),a.onclick=function(t){t.stopPropagation(),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(m){m.stopPropagation();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})}' +
  261. (this.autopause ? ',h.onplay=function(){for(var e,t=0;e=y[t];t++)e!=this&&e.pause()}' : '') +
  262. ';for(var _,p=document.getElementsByTagName("audio"),w=0;_=p[w];w++)_.onerror=function(){e({action:"error",source:"audio",target:this})};' +
  263. (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)}' : '') +
  264. '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)'
  265. )
  266. this.nodes = [1];
  267. // #endif
  268. // #ifdef H5 || MP-360
  269. if (!html) {
  270. if (this.rtf && !append) this.rtf.parentNode.removeChild(this.rtf);
  271. return;
  272. }
  273. var div = document.createElement('div');
  274. if (!append) {
  275. if (this.rtf) this.rtf.parentNode.removeChild(this.rtf);
  276. this.rtf = div;
  277. } else {
  278. if (!this.rtf) this.rtf = div;
  279. else this.rtf.appendChild(div);
  280. }
  281. div.innerHTML = this._handleHtml(html, append);
  282. for (var styles = this.rtf.getElementsByTagName('style'), i = 0, style; style = styles[i++];) {
  283. style.innerHTML = style.innerHTML.replace(/body/g, '#rtf' + this._uid);
  284. style.setAttribute('scoped', 'true');
  285. }
  286. // 懒加载
  287. if (!this._observer && this.lazyLoad && IntersectionObserver) {
  288. this._observer = new IntersectionObserver(changes => {
  289. for (let item, i = 0; item = changes[i++];) {
  290. if (item.isIntersecting) {
  291. item.target.src = item.target.getAttribute('data-src');
  292. item.target.removeAttribute('data-src');
  293. this._observer.unobserve(item.target);
  294. }
  295. }
  296. }, {
  297. rootMargin: '500px 0px 500px 0px'
  298. })
  299. }
  300. var _ts = this;
  301. // 获取标题
  302. var title = this.rtf.getElementsByTagName('title');
  303. if (title.length && this.autosetTitle)
  304. uni.setNavigationBarTitle({
  305. title: title[0].innerText
  306. })
  307. // 填充 domain
  308. var fill = target => {
  309. var src = target.getAttribute('src');
  310. if (this.domain && src) {
  311. if (src[0] == '/') {
  312. if (src[1] == '/')
  313. target.src = (this.domain.includes('://') ? this.domain.split('://')[0] : '') + ':' + src;
  314. else target.src = this.domain + src;
  315. } else if (!src.includes('://') && src.indexOf('data:') != 0) target.src = this.domain + '/' + src;
  316. }
  317. }
  318. // 图片处理
  319. this.imgList.length = 0;
  320. var imgs = this.rtf.getElementsByTagName('img');
  321. for (let i = 0, j = 0, img; img = imgs[i]; i++) {
  322. if (parseInt(img.style.width || img.getAttribute('width')) > windowWidth)
  323. img.style.height = 'auto';
  324. fill(img);
  325. if (!img.hasAttribute('ignore') && img.parentElement.nodeName != 'A') {
  326. img.i = j++;
  327. _ts.imgList.push(img.getAttribute('original-src') || img.src || img.getAttribute('data-src'));
  328. img.onclick = function(e) {
  329. e.stopPropagation();
  330. var preview = _ts.preview;
  331. this.ignore = () => preview = false;
  332. _ts.$emit('imgtap', this);
  333. if (preview) {
  334. uni.previewImage({
  335. current: this.i,
  336. urls: _ts.imgList
  337. });
  338. }
  339. }
  340. }
  341. img.onerror = function() {
  342. if (cfg.errorImg)
  343. _ts.imgList[this.i] = this.src = cfg.errorImg;
  344. _ts.$emit('error', {
  345. source: 'img',
  346. target: this
  347. });
  348. }
  349. if (_ts.lazyLoad && this._observer && img.src && img.i != 0) {
  350. img.setAttribute('data-src', img.src);
  351. img.removeAttribute('src');
  352. this._observer.observe(img);
  353. }
  354. }
  355. // 链接处理
  356. var links = this.rtf.getElementsByTagName('a');
  357. for (var link of links) {
  358. link.onclick = function(e) {
  359. e.stopPropagation();
  360. var jump = true,
  361. href = this.getAttribute('href');
  362. _ts.$emit('linkpress', {
  363. href,
  364. ignore: () => jump = false
  365. });
  366. if (jump && href) {
  367. if (href[0] == '#') {
  368. if (_ts.useAnchor) {
  369. _ts.navigateTo({
  370. id: href.substr(1)
  371. })
  372. }
  373. } else if (href.indexOf('http') == 0 || href.indexOf('//') == 0)
  374. return true;
  375. else
  376. uni.navigateTo({
  377. url: href
  378. })
  379. }
  380. return false;
  381. }
  382. }
  383. // 视频处理
  384. var videos = this.rtf.getElementsByTagName('video');
  385. _ts.videoContexts = videos;
  386. for (let video, i = 0; video = videos[i++];) {
  387. fill(video);
  388. video.style.maxWidth = '100%';
  389. video.onerror = function() {
  390. _ts.$emit('error', {
  391. source: 'video',
  392. target: this
  393. });
  394. }
  395. video.onplay = function() {
  396. if (_ts.autopause)
  397. for (let item, i = 0; item = _ts.videoContexts[i++];)
  398. if (item != this) item.pause();
  399. }
  400. }
  401. // 音频处理
  402. var audios = this.rtf.getElementsByTagName('audio');
  403. for (var audio of audios) {
  404. fill(audio);
  405. audio.onerror = function() {
  406. _ts.$emit('error', {
  407. source: 'audio',
  408. target: this
  409. });
  410. }
  411. }
  412. // 表格处理
  413. if (this.autoscroll) {
  414. var tables = this.rtf.getElementsByTagName('table');
  415. for (var table of tables) {
  416. let div = document.createElement('div');
  417. div.style.overflow = 'scroll';
  418. table.parentNode.replaceChild(div, table);
  419. div.appendChild(table);
  420. }
  421. }
  422. if (!append) this.document.appendChild(this.rtf);
  423. this.$nextTick(() => {
  424. this.nodes = [1];
  425. this.$emit('load');
  426. });
  427. setTimeout(() => this.showAm = '', 500);
  428. // #endif
  429. // #ifndef APP-PLUS-NVUE
  430. // #ifndef H5 || MP-360
  431. var nodes;
  432. if (!html) return this.nodes = [];
  433. var parser = new Parser(html, this);
  434. // 缓存读取
  435. if (this.useCache) {
  436. var hashVal = hash(html);
  437. if (cache[hashVal])
  438. nodes = cache[hashVal];
  439. else {
  440. nodes = parser.parse();
  441. cache[hashVal] = nodes;
  442. }
  443. } else nodes = parser.parse();
  444. this.$emit('parse', nodes);
  445. if (append) this.nodes = this.nodes.concat(nodes);
  446. else this.nodes = nodes;
  447. if (nodes.length && nodes.title && this.autosetTitle)
  448. uni.setNavigationBarTitle({
  449. title: nodes.title
  450. })
  451. if (this.imgList) this.imgList.length = 0;
  452. this.videoContexts = [];
  453. this.$nextTick(() => {
  454. (function f(cs) {
  455. for (var i = cs.length; i--;) {
  456. if (cs[i].top) {
  457. cs[i].controls = [];
  458. cs[i].init();
  459. f(cs[i].$children);
  460. }
  461. }
  462. })(this.$children)
  463. this.$emit('load');
  464. })
  465. // #endif
  466. var height;
  467. clearInterval(this._timer);
  468. this._timer = setInterval(() => {
  469. // #ifdef H5 || MP-360
  470. this.rect = this.rtf.getBoundingClientRect();
  471. // #endif
  472. // #ifndef H5 || MP-360
  473. uni.createSelectorQuery().in(this)
  474. .select('#_top').boundingClientRect().exec(res => {
  475. if (!res) return;
  476. this.rect = res[0];
  477. // #endif
  478. if (this.rect.height == height) {
  479. this.$emit('ready', this.rect)
  480. clearInterval(this._timer);
  481. }
  482. height = this.rect.height;
  483. // #ifndef H5 || MP-360
  484. });
  485. // #endif
  486. }, 350);
  487. if (this.showWithAnimation && !append) this.showAm = 'animation:_show .5s';
  488. // #endif
  489. },
  490. // 获取文本内容
  491. getText(ns = this.nodes) {
  492. var txt = '';
  493. // #ifdef APP-PLUS-NVUE
  494. txt = this._text;
  495. // #endif
  496. // #ifdef H5 || MP-360
  497. txt = this.rtf.innerText;
  498. // #endif
  499. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  500. for (var i = 0, n; n = ns[i++];) {
  501. if (n.type == 'text') txt += n.text.replace(/&nbsp;/g, '\u00A0').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  502. .replace(/&amp;/g, '&');
  503. else if (n.type == 'br') txt += '\n';
  504. else {
  505. // 块级标签前后加换行
  506. var block = n.name == 'p' || n.name == 'div' || n.name == 'tr' || n.name == 'li' || (n.name[0] == 'h' && n.name[1] >
  507. '0' && n.name[1] < '7');
  508. if (block && txt && txt[txt.length - 1] != '\n') txt += '\n';
  509. if (n.children) txt += this.getText(n.children);
  510. if (block && txt[txt.length - 1] != '\n') txt += '\n';
  511. else if (n.name == 'td' || n.name == 'th') txt += '\t';
  512. }
  513. }
  514. // #endif
  515. return txt;
  516. },
  517. // 锚点跳转
  518. in (obj) {
  519. if (obj.page && obj.selector && obj.scrollTop) this._in = obj;
  520. },
  521. navigateTo(obj) {
  522. if (!this.useAnchor) return obj.fail && obj.fail('Anchor is disabled');
  523. // #ifdef APP-PLUS-NVUE
  524. if (!obj.id)
  525. weexDom.scrollToElement(this.$refs.web);
  526. else
  527. this.$refs.web.evalJs('var pos=document.getElementById("' + obj.id +
  528. '");if(pos)post({action:"linkpress",href:"#",offset:pos.offsetTop+' + (obj.offset || 0) + '})');
  529. obj.success && obj.success();
  530. // #endif
  531. // #ifndef APP-PLUS-NVUE
  532. var d = ' ';
  533. // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
  534. d = '>>>';
  535. // #endif
  536. var selector = uni.createSelectorQuery().in(this._in ? this._in.page : this).select((this._in ? this._in.selector :
  537. '#_top') + (obj.id ? `${d}#${obj.id},${this._in?this._in.selector:'#_top'}${d}.${obj.id}` : '')).boundingClientRect();
  538. if (this._in) selector.select(this._in.selector).scrollOffset().select(this._in.selector).boundingClientRect();
  539. else selector.selectViewport().scrollOffset();
  540. selector.exec(res => {
  541. if (!res[0]) return obj.fail && obj.fail('Label not found')
  542. var scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + (obj.offset || 0);
  543. if (this._in) this._in.page[this._in.scrollTop] = scrollTop;
  544. else uni.pageScrollTo({
  545. scrollTop,
  546. duration: 300
  547. })
  548. obj.success && obj.success();
  549. })
  550. // #endif
  551. },
  552. // 获取视频对象
  553. getVideoContext(id) {
  554. // #ifndef APP-PLUS-NVUE
  555. if (!id) return this.videoContexts;
  556. else
  557. for (var i = this.videoContexts.length; i--;)
  558. if (this.videoContexts[i].id == id) return this.videoContexts[i];
  559. // #endif
  560. },
  561. // #ifdef H5 || APP-PLUS-NVUE || MP-360
  562. _handleHtml(html, append) {
  563. const classPrefix = ".u-parse ";
  564. if (!append) {
  565. // 处理 tag-style 和 userAgentStyles
  566. var style = `<style>@keyframes _show{0%{opacity:0}100%{opacity:1}}${classPrefix}img{max-width:100%}`;
  567. for (var item in cfg.userAgentStyles)
  568. style += `${classPrefix}${item}{${cfg.userAgentStyles[item]}}`;
  569. for (item in this.tagStyle)
  570. style += `${classPrefix}${item}{${this.tagStyle[item]}}`;
  571. style += '</style>';
  572. html = style + html;
  573. }
  574. // 处理 rpx
  575. if (html.includes('rpx'))
  576. html = html.replace(/[0-9.]+\s*rpx/g, $ => (parseFloat($) * windowWidth / 750) + 'px');
  577. return html;
  578. },
  579. // #endif
  580. // #ifdef APP-PLUS-NVUE
  581. _message(e) {
  582. var _ts = this;
  583. // 接收 web-view 消息
  584. var d = e.detail.data[0];
  585. switch (d.action) {
  586. case 'load':
  587. this.$emit('load');
  588. this.height = d.height;
  589. this._text = d.text;
  590. break;
  591. case 'getTitle':
  592. if (this.autosetTitle)
  593. uni.setNavigationBarTitle({
  594. title: d.title
  595. })
  596. break;
  597. case 'getImgList':
  598. this.imgList.length = 0;
  599. for (var i = d.imgList.length; i--;)
  600. this.imgList.setItem(i, d.imgList[i]);
  601. break;
  602. case 'preview':
  603. var preview = _ts.preview;
  604. d.img.ignore = () => preview = false;
  605. this.$emit('imgtap', d.img);
  606. if (preview)
  607. uni.previewImage({
  608. current: d.img.i,
  609. urls: this.imgList
  610. })
  611. break;
  612. case 'linkpress':
  613. var jump = true,
  614. href = d.href;
  615. this.$emit('linkpress', {
  616. href,
  617. ignore: () => jump = false
  618. })
  619. if (jump && href) {
  620. if (href[0] == '#') {
  621. if (this.useAnchor)
  622. weexDom.scrollToElement(this.$refs.web, {
  623. offset: d.offset
  624. })
  625. } else if (href.includes('://'))
  626. plus.runtime.openWeb(href);
  627. else
  628. uni.navigateTo({
  629. url: href
  630. })
  631. }
  632. break;
  633. case 'error':
  634. if (d.source == 'img' && cfg.errorImg)
  635. this.imgList.setItem(d.target.i, cfg.errorImg);
  636. this.$emit('error', {
  637. source: d.source,
  638. target: d.target
  639. })
  640. break;
  641. case 'ready':
  642. this.height = d.height;
  643. if (d.ready) uni.createSelectorQuery().in(this).select('#_top').boundingClientRect().exec(res => {
  644. this.rect = res[0];
  645. this.$emit('ready', res[0]);
  646. })
  647. break;
  648. case 'click':
  649. this.$emit('click');
  650. this.$emit('tap');
  651. }
  652. },
  653. // #endif
  654. }
  655. }
  656. </script>
  657. <style lang="scss" scoped>
  658. @keyframes _show {
  659. 0% {
  660. opacity: 0;
  661. }
  662. 100% {
  663. opacity: 1;
  664. }
  665. }
  666. /* #ifdef MP-WEIXIN */
  667. :host {
  668. display: block;
  669. overflow: auto;
  670. -webkit-overflow-scrolling: touch;
  671. }
  672. /* #endif */
  673. </style>