mui.previewimage.js 13 KB

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