mui.previewimage.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. (function($, window) {
  2. var template = '<div id="{{id}}" class="mui-slider mui-preview-image mui-fullscreen"><div class="mui-preview-header">{{header}}</div><div class="mui-slider-group"></div><div class="mui-preview-footer mui-hidden">{{footer}}</div><div class="mui-preview-loading"><span class="mui-spinner mui-spinner-white"></span></div></div>';
  3. var itemTemplate = '<div class="mui-slider-item mui-zoom-wrapper {{className}}"><div class="mui-zoom-scroller"><img src="{{src}}" data-code="{{code}}" data-preview-lazyload="{{lazyload}}" style="{{style}}" class="mui-zoom"></div></div>';
  4. var defaultGroupName = '__DEFAULT';
  5. var div = document.createElement('div');
  6. var imgId = 0;
  7. var PreviewImage = function(options) {
  8. this.options = $.extend(true, {
  9. id: '__MUI_PREVIEWIMAGE',
  10. zoom: true,
  11. header: '<span class="mui-preview-indicator"></span>',
  12. footer: ''
  13. }, options || {});
  14. this.init();
  15. this.initEvent();
  16. };
  17. var proto = PreviewImage.prototype;
  18. proto.init = function() {
  19. var options = this.options;
  20. var el = document.getElementById(this.options.id);
  21. if (!el) {
  22. div.innerHTML = template.replace(/\{\{id\}\}/g, this.options.id).replace('{{header}}', options.header).replace('{{footer}}', options.footer);
  23. document.body.appendChild(div.firstElementChild);
  24. el = document.getElementById(this.options.id);
  25. }
  26. this.element = el;
  27. this.scroller = this.element.querySelector($.classSelector('.slider-group'));
  28. this.indicator = this.element.querySelector($.classSelector('.preview-indicator'));
  29. this.loader = this.element.querySelector($.classSelector('.preview-loading'));
  30. if (options.footer) {
  31. this.element.querySelector($.classSelector('.preview-footer')).classList.remove($.className('hidden'));
  32. }
  33. this.addImages();
  34. };
  35. proto.initEvent = function() {
  36. var self = this;
  37. $(document.body).on('tap', 'img[data-preview-src]', function() {
  38. if (self.isAnimationing()) {
  39. return false;
  40. }
  41. self.open(this);
  42. return false;
  43. });
  44. var laterClose = null;
  45. var laterCloseEvent = function() {
  46. !laterClose && (laterClose = $.later(function() {
  47. self.isInAnimation = true;
  48. self.loader.removeEventListener('tap', laterCloseEvent);
  49. self.scroller.removeEventListener('tap', laterCloseEvent);
  50. self.close();
  51. }, 300));
  52. };
  53. this.scroller.addEventListener('doubletap', function() {
  54. if (laterClose) {
  55. laterClose.cancel();
  56. laterClose = null;
  57. }
  58. });
  59. this.element.addEventListener('webkitAnimationEnd', function() {
  60. if (self.element.classList.contains($.className('preview-out'))) { //close
  61. self.element.style.display = 'none';
  62. self.element.classList.remove($.className('preview-out'));
  63. laterClose = null;
  64. } else { //open
  65. self.loader.addEventListener('tap', laterCloseEvent);
  66. self.scroller.addEventListener('tap', laterCloseEvent);
  67. }
  68. self.isInAnimation = false;
  69. });
  70. this.element.addEventListener('slide', function(e) {
  71. if (self.options.zoom) {
  72. var lastZoomerEl = self.element.querySelector('.mui-zoom-wrapper:nth-child(' + (self.lastIndex + 1) + ')');
  73. if (lastZoomerEl) {
  74. $(lastZoomerEl).zoom().setZoom(1);
  75. }
  76. }
  77. var slideNumber = e.detail.slideNumber;
  78. self.lastIndex = slideNumber;
  79. self.indicator && (self.indicator.innerText = (slideNumber + 1) + '/' + self.currentGroup.length);
  80. self._loadItem(slideNumber);
  81. });
  82. };
  83. proto.isAnimationing = function() {
  84. if (this.isInAnimation) {
  85. return true;
  86. }
  87. this.isInAnimation = true;
  88. return false;
  89. };
  90. proto.addImages = function(group, index) {
  91. this.groups = {};
  92. var imgs = [];
  93. if (group) {
  94. if (group === defaultGroupName) {
  95. imgs = document.querySelectorAll("img[data-preview-src]:not([data-preview-group])");
  96. } else {
  97. imgs = document.querySelectorAll("img[data-preview-src][data-preview-group='" + group + "']");
  98. }
  99. } else {
  100. imgs = document.querySelectorAll("img[data-preview-src]");
  101. }
  102. if (imgs.length) {
  103. for (var i = 0, len = imgs.length; i < len; i++) {
  104. this.addImage(imgs[i]);
  105. }
  106. }
  107. };
  108. proto.addImage = function(img) {
  109. var group = img.getAttribute('data-preview-group');
  110. group = group || defaultGroupName;
  111. if (!this.groups[group]) {
  112. this.groups[group] = [];
  113. }
  114. var src = img.getAttribute('src');
  115. if (img.__mui_img_data && img.__mui_img_data.src === src) { //已缓存且图片未变化
  116. this.groups[group].push(img.__mui_img_data);
  117. } else {
  118. var lazyload = img.getAttribute('data-preview-src');
  119. if (!lazyload) {
  120. lazyload = src;
  121. }
  122. var imgObj = {
  123. src: src,
  124. lazyload: src === lazyload ? '' : lazyload,
  125. loaded: src === lazyload ? true : false,
  126. sWidth: 0,
  127. sHeight: 0,
  128. sTop: 0,
  129. sLeft: 0,
  130. sScale: 1,
  131. code: img.getAttribute('data-code'),
  132. el: img
  133. };
  134. this.groups[group].push(imgObj);
  135. img.__mui_img_data = imgObj;
  136. }
  137. };
  138. proto.empty = function() {
  139. this.scroller.innerHTML = '';
  140. };
  141. proto._initImgData = function(itemData, imgEl) {
  142. if (!itemData.sWidth) {
  143. var img = itemData.el;
  144. itemData.sWidth = img.offsetWidth;
  145. itemData.sHeight = img.offsetHeight;
  146. var offset = $.offset(img);
  147. itemData.sTop = offset.top;
  148. itemData.sLeft = offset.left;
  149. itemData.sScale = Math.max(itemData.sWidth / window.innerWidth, itemData.sHeight / window.innerHeight);
  150. }
  151. imgEl.style.webkitTransform = 'translate3d(0,0,0) scale(' + itemData.sScale + ')';
  152. };
  153. proto._getScale = function(from, to) {
  154. var scaleX = from.width / to.width;
  155. var scaleY = from.height / to.height;
  156. var scale = 1;
  157. if (scaleX <= scaleY) {
  158. scale = from.height / (to.height * scaleX);
  159. } else {
  160. scale = from.width / (to.width * scaleY);
  161. }
  162. return scale;
  163. };
  164. proto._imgTransitionEnd = function(e) {
  165. var img = e.target;
  166. img.classList.remove($.className('transitioning'));
  167. img.removeEventListener('webkitTransitionEnd', this._imgTransitionEnd.bind(this));
  168. };
  169. proto._loadItem = function(index, isOpening) { //TODO 暂时仅支持img
  170. var itemEl = this.scroller.querySelector($.classSelector('.slider-item:nth-child(' + (index + 1) + ')'));
  171. var itemData = this.currentGroup[index];
  172. var imgEl = itemEl.querySelector('img');
  173. this._initImgData(itemData, imgEl);
  174. if (isOpening) {
  175. var posi = this._getPosition(itemData);
  176. imgEl.style.webkitTransitionDuration = '0ms';
  177. imgEl.style.webkitTransform = 'translate3d(' + posi.x + 'px,' + posi.y + 'px,0) scale(' + itemData.sScale + ')';
  178. imgEl.offsetHeight;
  179. }
  180. if (!itemData.loaded && imgEl.getAttribute('data-preview-lazyload')) {
  181. var self = this;
  182. self.loader.classList.add($.className('active'));
  183. //移动位置动画
  184. imgEl.style.webkitTransitionDuration = '0.5s';
  185. imgEl.addEventListener('webkitTransitionEnd', self._imgTransitionEnd.bind(self));
  186. imgEl.style.webkitTransform = 'translate3d(0,0,0) scale(' + itemData.sScale + ')';
  187. this.loadImage(imgEl, function() {
  188. itemData.loaded = true;
  189. imgEl.src = itemData.lazyload;
  190. self._initZoom(itemEl, this.width, this.height);
  191. imgEl.classList.add($.className('transitioning'));
  192. imgEl.addEventListener('webkitTransitionEnd', self._imgTransitionEnd.bind(self));
  193. imgEl.setAttribute('style', '');
  194. imgEl.offsetHeight;
  195. self.loader.classList.remove($.className('active'));
  196. });
  197. } else {
  198. itemData.lazyload && (imgEl.src = itemData.lazyload);
  199. this._initZoom(itemEl, imgEl.width, imgEl.height);
  200. imgEl.classList.add($.className('transitioning'));
  201. imgEl.addEventListener('webkitTransitionEnd', this._imgTransitionEnd.bind(this));
  202. imgEl.setAttribute('style', '');
  203. imgEl.offsetHeight;
  204. }
  205. this._preloadItem(index + 1);
  206. this._preloadItem(index - 1);
  207. };
  208. proto._preloadItem = function(index) {
  209. var itemEl = this.scroller.querySelector($.classSelector('.slider-item:nth-child(' + (index + 1) + ')'));
  210. if (itemEl) {
  211. var itemData = this.currentGroup[index];
  212. if (!itemData.sWidth) {
  213. var imgEl = itemEl.querySelector('img');
  214. this._initImgData(itemData, imgEl);
  215. }
  216. }
  217. };
  218. proto._initZoom = function(zoomWrapperEl, zoomerWidth, zoomerHeight) {
  219. if (!this.options.zoom) {
  220. return;
  221. }
  222. if (zoomWrapperEl.getAttribute('data-zoomer')) {
  223. return;
  224. }
  225. var zoomEl = zoomWrapperEl.querySelector($.classSelector('.zoom'));
  226. if (zoomEl.tagName === 'IMG') {
  227. var self = this;
  228. var maxZoom = self._getScale({
  229. width: zoomWrapperEl.offsetWidth,
  230. height: zoomWrapperEl.offsetHeight
  231. }, {
  232. width: zoomerWidth,
  233. height: zoomerHeight
  234. });
  235. $(zoomWrapperEl).zoom({
  236. maxZoom: Math.max(maxZoom, 1)
  237. });
  238. } else {
  239. $(zoomWrapperEl).zoom();
  240. }
  241. };
  242. proto.loadImage = function(imgEl, callback) {
  243. var onReady = function() {
  244. callback && callback.call(this);
  245. };
  246. var img = new Image();
  247. img.onload = onReady;
  248. img.onerror = onReady;
  249. img.src = imgEl.getAttribute('data-preview-lazyload');
  250. };
  251. proto.getRangeByIndex = function(index, length) {
  252. return {
  253. from: 0,
  254. to: length - 1
  255. };
  256. // var from = Math.max(index - 1, 0);
  257. // var to = Math.min(index + 1, length);
  258. // if (index === length - 1) {
  259. // from = Math.max(length - 3, 0);
  260. // to = length - 1;
  261. // }
  262. // if (index === 0) {
  263. // from = 0;
  264. // to = Math.min(2, length - 1);
  265. // }
  266. // return {
  267. // from: from,
  268. // to: to
  269. // };
  270. };
  271. proto._getPosition = function(itemData) {
  272. var sLeft = itemData.sLeft - window.pageXOffset;
  273. var sTop = itemData.sTop - window.pageYOffset;
  274. var left = (window.innerWidth - itemData.sWidth) / 2;
  275. var top = (window.innerHeight - itemData.sHeight) / 2;
  276. return {
  277. left: sLeft,
  278. top: sTop,
  279. x: sLeft - left,
  280. y: sTop - top
  281. };
  282. };
  283. proto.refresh = function(index, groupArray) {
  284. this.currentGroup = groupArray;
  285. //重新生成slider
  286. var length = groupArray.length;
  287. var itemHtml = [];
  288. var currentRange = this.getRangeByIndex(index, length);
  289. var from = currentRange.from;
  290. var to = currentRange.to + 1;
  291. var currentIndex = index;
  292. var className = '';
  293. var itemStr = '';
  294. var wWidth = window.innerWidth;
  295. var wHeight = window.innerHeight;
  296. for (var i = 0; from < to; from++, i++) {
  297. var itemData = groupArray[from];
  298. var style = '';
  299. if (itemData.sWidth) {
  300. style = '-webkit-transform:translate3d(0,0,0) scale(' + itemData.sScale + ');transform:translate3d(0,0,0) scale(' + itemData.sScale + ')';
  301. }
  302. itemStr = itemTemplate.replace('{{src}}', itemData.src).replace('{{code}}', itemData.code).replace('{{lazyload}}', itemData.lazyload).replace('{{style}}', style);
  303. if (from === index) {
  304. currentIndex = i;
  305. className = $.className('active');
  306. } else {
  307. className = '';
  308. }
  309. itemHtml.push(itemStr.replace('{{className}}', className));
  310. }
  311. this.scroller.innerHTML = itemHtml.join('');
  312. this.element.style.display = 'block';
  313. this.element.classList.add($.className('preview-in'));
  314. this.lastIndex = currentIndex;
  315. this.element.offsetHeight;
  316. $(this.element).slider().gotoItem(currentIndex, 0);
  317. this.indicator && (this.indicator.innerText = (currentIndex + 1) + '/' + this.currentGroup.length);
  318. this._loadItem(currentIndex, true);
  319. };
  320. proto.openByGroup = function(index, group) {
  321. index = Math.min(Math.max(0, index), this.groups[group].length - 1);
  322. this.refresh(index, this.groups[group]);
  323. };
  324. proto.open = function(index, group) {
  325. if (this.element.classList.contains($.className('preview-in'))) {
  326. return;
  327. }
  328. if (typeof index === "number") {
  329. group = group || defaultGroupName;
  330. this.addImages(group, index); //刷新当前group
  331. this.openByGroup(index, group);
  332. } else {
  333. group = index.getAttribute('data-preview-group');
  334. group = group || defaultGroupName;
  335. this.addImages(group, index); //刷新当前group
  336. this.openByGroup(this.groups[group].indexOf(index.__mui_img_data), group);
  337. }
  338. };
  339. proto.close = function(index, group) {
  340. if(this.lastIndex==undefined)
  341. return;
  342. this.element.classList.remove($.className('preview-in'));
  343. this.element.classList.add($.className('preview-out'));
  344. var itemEl = this.scroller.querySelector($.classSelector('.slider-item:nth-child(' + (this.lastIndex + 1) + ')'));
  345. var imgEl = itemEl.querySelector('img');
  346. if (imgEl) {
  347. imgEl.classList.add($.className('transitioning'));
  348. var itemData = this.currentGroup[this.lastIndex];
  349. var posi = this._getPosition(itemData);
  350. var sLeft = posi.left;
  351. var sTop = posi.top;
  352. if (sTop > window.innerHeight || sLeft > window.innerWidth || sTop < 0 || sLeft < 0) { //out viewport
  353. imgEl.style.opacity = 0;
  354. imgEl.style.webkitTransitionDuration = '0.5s';
  355. imgEl.style.webkitTransform = 'scale(' + itemData.sScale + ')';
  356. } else {
  357. if (this.options.zoom) {
  358. $(imgEl.parentNode.parentNode).zoom().toggleZoom(0);
  359. }
  360. imgEl.style.webkitTransitionDuration = '0.5s';
  361. imgEl.style.webkitTransform = 'translate3d(' + posi.x + 'px,' + posi.y + 'px,0) scale(' + itemData.sScale + ')';
  362. }
  363. }
  364. var zoomers = this.element.querySelectorAll($.classSelector('.zoom-wrapper'));
  365. for (var i = 0, len = zoomers.length; i < len; i++) {
  366. $(zoomers[i]).zoom().destory();
  367. }
  368. // $(this.element).slider().destory();
  369. // this.empty();
  370. };
  371. proto.isShown = function() {
  372. return this.element.classList.contains($.className('preview-in'));
  373. };
  374. var previewImageApi = null;
  375. $.previewImage = function(options) {
  376. if (!previewImageApi) {
  377. previewImageApi = new PreviewImage(options);
  378. }
  379. return previewImageApi;
  380. };
  381. $.getPreviewImage = function() {
  382. return previewImageApi;
  383. }
  384. })(mui, window);