spin.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. //fgnass.github.com/spin.js#v1.2.7
  2. !function(window, document, undefined) {
  3. /**
  4. * Copyright (c) 2011 Felix Gnass [fgnass at neteye dot de]
  5. * Licensed under the MIT license
  6. */
  7. var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */
  8. , animations = {} /* Animation rules keyed by their name */
  9. , useCssAnimations
  10. /**
  11. * Utility function to create elements. If no tag name is given,
  12. * a DIV is created. Optionally properties can be passed.
  13. */
  14. function createEl(tag, prop) {
  15. var el = document.createElement(tag || 'div')
  16. , n
  17. for(n in prop) el[n] = prop[n]
  18. return el
  19. }
  20. /**
  21. * Appends children and returns the parent.
  22. */
  23. function ins(parent /* child1, child2, ...*/) {
  24. for (var i=1, n=arguments.length; i<n; i++)
  25. parent.appendChild(arguments[i])
  26. return parent
  27. }
  28. /**
  29. * Insert a new stylesheet to hold the @keyframe or VML rules.
  30. */
  31. var sheet = function() {
  32. var el = createEl('style', {type : 'text/css'})
  33. ins(document.getElementsByTagName('head')[0], el)
  34. return el.sheet || el.styleSheet
  35. }()
  36. /**
  37. * Creates an opacity keyframe animation rule and returns its name.
  38. * Since most mobile Webkits have timing issues with animation-delay,
  39. * we create separate rules for each line/segment.
  40. */
  41. function addAnimation(alpha, trail, i, lines) {
  42. var name = ['opacity', trail, ~~(alpha*100), i, lines].join('-')
  43. , start = 0.01 + i/lines*100
  44. , z = Math.max(1 - (1-alpha) / trail * (100-start), alpha)
  45. , prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase()
  46. , pre = prefix && '-'+prefix+'-' || ''
  47. if (!animations[name]) {
  48. sheet.insertRule(
  49. '@' + pre + 'keyframes ' + name + '{' +
  50. '0%{opacity:' + z + '}' +
  51. start + '%{opacity:' + alpha + '}' +
  52. (start+0.01) + '%{opacity:1}' +
  53. (start+trail) % 100 + '%{opacity:' + alpha + '}' +
  54. '100%{opacity:' + z + '}' +
  55. '}', sheet.cssRules.length)
  56. animations[name] = 1
  57. }
  58. return name
  59. }
  60. /**
  61. * Tries various vendor prefixes and returns the first supported property.
  62. **/
  63. function vendor(el, prop) {
  64. var s = el.style
  65. , pp
  66. , i
  67. if(s[prop] !== undefined) return prop
  68. prop = prop.charAt(0).toUpperCase() + prop.slice(1)
  69. for(i=0; i<prefixes.length; i++) {
  70. pp = prefixes[i]+prop
  71. if(s[pp] !== undefined) return pp
  72. }
  73. }
  74. /**
  75. * Sets multiple style properties at once.
  76. */
  77. function css(el, prop) {
  78. for (var n in prop)
  79. el.style[vendor(el, n)||n] = prop[n]
  80. return el
  81. }
  82. /**
  83. * Fills in default values.
  84. */
  85. function merge(obj) {
  86. for (var i=1; i < arguments.length; i++) {
  87. var def = arguments[i]
  88. for (var n in def)
  89. if (obj[n] === undefined) obj[n] = def[n]
  90. }
  91. return obj
  92. }
  93. /**
  94. * Returns the absolute page-offset of the given element.
  95. */
  96. function pos(el) {
  97. var o = { x:el.offsetLeft, y:el.offsetTop }
  98. while((el = el.offsetParent))
  99. o.x+=el.offsetLeft, o.y+=el.offsetTop
  100. return o
  101. }
  102. var defaults = {
  103. lines: 12, // The number of lines to draw
  104. length: 7, // The length of each line
  105. width: 5, // The line thickness
  106. radius: 10, // The radius of the inner circle
  107. rotate: 0, // Rotation offset
  108. corners: 1, // Roundness (0..1)
  109. color: '#000', // #rgb or #rrggbb
  110. speed: 1, // Rounds per second
  111. trail: 100, // Afterglow percentage
  112. opacity: 1/4, // Opacity of the lines
  113. fps: 20, // Frames per second when using setTimeout()
  114. zIndex: 2e9, // Use a high z-index by default
  115. className: 'spinner', // CSS class to assign to the element
  116. top: 'auto', // center vertically
  117. left: 'auto', // center horizontally
  118. position: 'relative' // element position
  119. }
  120. /** The constructor */
  121. var Spinner = function Spinner(o) {
  122. if (!this.spin) return new Spinner(o)
  123. this.opts = merge(o || {}, Spinner.defaults, defaults)
  124. }
  125. Spinner.defaults = {}
  126. merge(Spinner.prototype, {
  127. spin: function(target) {
  128. this.stop()
  129. var self = this
  130. , o = self.opts
  131. , el = self.el = css(createEl(0, {className: o.className}), {position: o.position, width: 0, zIndex: o.zIndex})
  132. , mid = o.radius+o.length+o.width
  133. , ep // element position
  134. , tp // target position
  135. if (target) {
  136. target.insertBefore(el, target.firstChild||null)
  137. tp = pos(target)
  138. ep = pos(el)
  139. css(el, {
  140. left: (o.left == 'auto' ? tp.x-ep.x + (target.offsetWidth >> 1) : parseInt(o.left, 10) + mid) + 'px',
  141. top: (o.top == 'auto' ? tp.y-ep.y + (target.offsetHeight >> 1) : parseInt(o.top, 10) + mid) + 'px'
  142. })
  143. }
  144. el.setAttribute('aria-role', 'progressbar')
  145. self.lines(el, self.opts)
  146. if (!useCssAnimations) {
  147. // No CSS animation support, use setTimeout() instead
  148. var i = 0
  149. , fps = o.fps
  150. , f = fps/o.speed
  151. , ostep = (1-o.opacity) / (f*o.trail / 100)
  152. , astep = f/o.lines
  153. ;(function anim() {
  154. i++;
  155. for (var s=o.lines; s; s--) {
  156. var alpha = Math.max(1-(i+s*astep)%f * ostep, o.opacity)
  157. self.opacity(el, o.lines-s, alpha, o)
  158. }
  159. self.timeout = self.el && setTimeout(anim, ~~(1000/fps))
  160. })()
  161. }
  162. return self
  163. },
  164. stop: function() {
  165. var el = this.el
  166. if (el) {
  167. clearTimeout(this.timeout)
  168. if (el.parentNode) el.parentNode.removeChild(el)
  169. this.el = undefined
  170. }
  171. return this
  172. },
  173. lines: function(el, o) {
  174. var i = 0
  175. , seg
  176. function fill(color, shadow) {
  177. return css(createEl(), {
  178. position: 'absolute',
  179. width: (o.length+o.width) + 'px',
  180. height: o.width + 'px',
  181. background: color,
  182. boxShadow: shadow,
  183. transformOrigin: 'left',
  184. transform: 'rotate(' + ~~(360/o.lines*i+o.rotate) + 'deg) translate(' + o.radius+'px' +',0)',
  185. borderRadius: (o.corners * o.width>>1) + 'px'
  186. })
  187. }
  188. for (; i < o.lines; i++) {
  189. seg = css(createEl(), {
  190. position: 'absolute',
  191. top: 1+~(o.width/2) + 'px',
  192. transform: o.hwaccel ? 'translate3d(0,0,0)' : '',
  193. opacity: o.opacity,
  194. animation: useCssAnimations && addAnimation(o.opacity, o.trail, i, o.lines) + ' ' + 1/o.speed + 's linear infinite'
  195. })
  196. if (o.shadow) ins(seg, css(fill('#000', '0 0 4px ' + '#000'), {top: 2+'px'}))
  197. ins(el, ins(seg, fill(o.color, '0 0 1px rgba(0,0,0,.1)')))
  198. }
  199. return el
  200. },
  201. opacity: function(el, i, val) {
  202. if (i < el.childNodes.length) el.childNodes[i].style.opacity = val
  203. }
  204. })
  205. /////////////////////////////////////////////////////////////////////////
  206. // VML rendering for IE
  207. /////////////////////////////////////////////////////////////////////////
  208. /**
  209. * Check and init VML support
  210. */
  211. ;(function() {
  212. function vml(tag, attr) {
  213. return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr)
  214. }
  215. var s = css(createEl('group'), {behavior: 'url(#default#VML)'})
  216. if (!vendor(s, 'transform') && s.adj) {
  217. // VML support detected. Insert CSS rule ...
  218. sheet.addRule('.spin-vml', 'behavior:url(#default#VML)')
  219. Spinner.prototype.lines = function(el, o) {
  220. var r = o.length+o.width
  221. , s = 2*r
  222. function grp() {
  223. return css(
  224. vml('group', {
  225. coordsize: s + ' ' + s,
  226. coordorigin: -r + ' ' + -r
  227. }),
  228. { width: s, height: s }
  229. )
  230. }
  231. var margin = -(o.width+o.length)*2 + 'px'
  232. , g = css(grp(), {position: 'absolute', top: margin, left: margin})
  233. , i
  234. function seg(i, dx, filter) {
  235. ins(g,
  236. ins(css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}),
  237. ins(css(vml('roundrect', {arcsize: o.corners}), {
  238. width: r,
  239. height: o.width,
  240. left: o.radius,
  241. top: -o.width>>1,
  242. filter: filter
  243. }),
  244. vml('fill', {color: o.color, opacity: o.opacity}),
  245. vml('stroke', {opacity: 0}) // transparent stroke to fix color bleeding upon opacity change
  246. )
  247. )
  248. )
  249. }
  250. if (o.shadow)
  251. for (i = 1; i <= o.lines; i++)
  252. seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)')
  253. for (i = 1; i <= o.lines; i++) seg(i)
  254. return ins(el, g)
  255. }
  256. Spinner.prototype.opacity = function(el, i, val, o) {
  257. var c = el.firstChild
  258. o = o.shadow && o.lines || 0
  259. if (c && i+o < c.childNodes.length) {
  260. c = c.childNodes[i+o]; c = c && c.firstChild; c = c && c.firstChild
  261. if (c) c.opacity = val
  262. }
  263. }
  264. }
  265. else
  266. useCssAnimations = vendor(s, 'animation')
  267. })()
  268. if (typeof define == 'function' && define.amd)
  269. define(function() { return Spinner })
  270. else
  271. window.Spinner = Spinner
  272. }(window, document);