loading.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. (function (root, factory) {
  2. //amd
  3. if (typeof define === 'function' && define.amd) {
  4. define(['jquery'], factory);
  5. } else if (typeof exports === 'object') { //umd
  6. module.exports = factory($);
  7. } else {
  8. root.Loading = factory(window.Zepto || window.jQuery || $);
  9. }
  10. })(window, function ($) {
  11. var Loading = function () { };
  12. Loading.prototype = {
  13. loadingTpl: '<div class="ui-loading"><div class="ui-loading-mask"></div><i></i></div>',
  14. stop: function () {
  15. this.loading.remove();
  16. this.loading = null;
  17. },
  18. start: function () {
  19. var _this = this;
  20. var loading = this.loading;
  21. if (!loading) {
  22. loading = $(_this.loadingTpl);
  23. $('body').append(loading);
  24. }
  25. this.loading = loading;
  26. //console.log(cw,ch)
  27. this.setPosition();
  28. },
  29. setPosition: function () {
  30. var _this = this;
  31. var loading = this.loading;
  32. var target = _this.target;
  33. var content = $(target);
  34. var ch = $(content).outerHeight();
  35. var cw = $(content).outerWidth();
  36. if ($(target)[0].tagName == "HTML") {
  37. ch = Math.max($(target).height(), $(window).height());
  38. cw = Math.max($(target).width(), $(window).width());
  39. }
  40. loading.height(ch).width(cw);
  41. loading.find('div').height(ch).width(cw);
  42. if (ch < 100) {
  43. loading.find('i').height(ch).width(ch);
  44. }
  45. var offset = $(content).offset();
  46. loading.css({
  47. top: offset.top,
  48. left: offset.left
  49. });
  50. var icon = loading.find('i');
  51. var h = ch,
  52. w = cw,
  53. top = 0,
  54. left = 0;
  55. if ($(target)[0].tagName == "HTML") {
  56. h = $(window).height();
  57. w = $(window).width();
  58. top = (h - icon.height()) / 2 + $(window).scrollTop();
  59. left = (w - icon.width()) / 2 + $(window).scrollLeft();
  60. } else {
  61. top = (h - icon.height()) / 2;
  62. left = (w - icon.width()) / 2;
  63. }
  64. icon.css({
  65. top: top,
  66. left: left
  67. })
  68. },
  69. init: function (settings) {
  70. settings = settings || {};
  71. this.loadingTpl = settings.loadingTpl || this.loadingTpl;
  72. this.target = settings.target || 'html';
  73. this.bindEvent();
  74. },
  75. bindEvent: function () {
  76. var _this = this;
  77. $(this.target).on('stop', function () {
  78. _this.stop();
  79. });
  80. $(window).on('resize', function () {
  81. _this.loading && _this.setPosition();
  82. });
  83. }
  84. }
  85. return Loading;
  86. });