u-parse.vue 21 KB

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