zepto.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. /* Zepto v1.2.0 - zepto event ajax form ie - zeptojs.com/license */
  2. (function(global, factory) {
  3. if (typeof define === 'function' && define.amd)
  4. define(function() { return factory(global) })
  5. else
  6. factory(global)
  7. }(this, function(window) {
  8. var Zepto = (function() {
  9. var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice,
  10. document = window.document,
  11. elementDisplay = {}, classCache = {},
  12. cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
  13. fragmentRE = /^\s*<(\w+|!)[^>]*>/,
  14. singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
  15. tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
  16. rootNodeRE = /^(?:body|html)$/i,
  17. capitalRE = /([A-Z])/g,
  18. // special attributes that should be get/set via method calls
  19. methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
  20. adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
  21. table = document.createElement('table'),
  22. tableRow = document.createElement('tr'),
  23. containers = {
  24. 'tr': document.createElement('tbody'),
  25. 'tbody': table, 'thead': table, 'tfoot': table,
  26. 'td': tableRow, 'th': tableRow,
  27. '*': document.createElement('div')
  28. },
  29. readyRE = /complete|loaded|interactive/,
  30. simpleSelectorRE = /^[\w-]*$/,
  31. class2type = {},
  32. toString = class2type.toString,
  33. zepto = {},
  34. camelize, uniq,
  35. tempParent = document.createElement('div'),
  36. propMap = {
  37. 'tabindex': 'tabIndex',
  38. 'readonly': 'readOnly',
  39. 'for': 'htmlFor',
  40. 'class': 'className',
  41. 'maxlength': 'maxLength',
  42. 'cellspacing': 'cellSpacing',
  43. 'cellpadding': 'cellPadding',
  44. 'rowspan': 'rowSpan',
  45. 'colspan': 'colSpan',
  46. 'usemap': 'useMap',
  47. 'frameborder': 'frameBorder',
  48. 'contenteditable': 'contentEditable'
  49. },
  50. isArray = Array.isArray ||
  51. function(object){ return object instanceof Array }
  52. zepto.matches = function(element, selector) {
  53. if (!selector || !element || element.nodeType !== 1) return false
  54. var matchesSelector = element.matches || element.webkitMatchesSelector ||
  55. element.mozMatchesSelector || element.oMatchesSelector ||
  56. element.matchesSelector
  57. if (matchesSelector) return matchesSelector.call(element, selector)
  58. // fall back to performing a selector:
  59. var match, parent = element.parentNode, temp = !parent
  60. if (temp) (parent = tempParent).appendChild(element)
  61. match = ~zepto.qsa(parent, selector).indexOf(element)
  62. temp && tempParent.removeChild(element)
  63. return match
  64. }
  65. function type(obj) {
  66. return obj == null ? String(obj) :
  67. class2type[toString.call(obj)] || "object"
  68. }
  69. function isFunction(value) { return type(value) == "function" }
  70. function isWindow(obj) { return obj != null && obj == obj.window }
  71. function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
  72. function isObject(obj) { return type(obj) == "object" }
  73. function isPlainObject(obj) {
  74. return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
  75. }
  76. function likeArray(obj) {
  77. var length = !!obj && 'length' in obj && obj.length,
  78. type = $.type(obj)
  79. return 'function' != type && !isWindow(obj) && (
  80. 'array' == type || length === 0 ||
  81. (typeof length == 'number' && length > 0 && (length - 1) in obj)
  82. )
  83. }
  84. function compact(array) { return filter.call(array, function(item){ return item != null }) }
  85. function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
  86. camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
  87. function dasherize(str) {
  88. return str.replace(/::/g, '/')
  89. .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
  90. .replace(/([a-z\d])([A-Z])/g, '$1_$2')
  91. .replace(/_/g, '-')
  92. .toLowerCase()
  93. }
  94. uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
  95. function classRE(name) {
  96. return name in classCache ?
  97. classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
  98. }
  99. function maybeAddPx(name, value) {
  100. return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
  101. }
  102. function defaultDisplay(nodeName) {
  103. var element, display
  104. if (!elementDisplay[nodeName]) {
  105. element = document.createElement(nodeName)
  106. document.body.appendChild(element)
  107. display = getComputedStyle(element, '').getPropertyValue("display")
  108. element.parentNode.removeChild(element)
  109. display == "none" && (display = "block")
  110. elementDisplay[nodeName] = display
  111. }
  112. return elementDisplay[nodeName]
  113. }
  114. function children(element) {
  115. return 'children' in element ?
  116. slice.call(element.children) :
  117. $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
  118. }
  119. function Z(dom, selector) {
  120. var i, len = dom ? dom.length : 0
  121. for (i = 0; i < len; i++) this[i] = dom[i]
  122. this.length = len
  123. this.selector = selector || ''
  124. }
  125. // `$.zepto.fragment` takes a html string and an optional tag name
  126. // to generate DOM nodes from the given html string.
  127. // The generated DOM nodes are returned as an array.
  128. // This function can be overridden in plugins for example to make
  129. // it compatible with browsers that don't support the DOM fully.
  130. zepto.fragment = function(html, name, properties) {
  131. var dom, nodes, container
  132. // A special case optimization for a single tag
  133. if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
  134. if (!dom) {
  135. if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
  136. if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
  137. if (!(name in containers)) name = '*'
  138. container = containers[name]
  139. container.innerHTML = '' + html
  140. dom = $.each(slice.call(container.childNodes), function(){
  141. container.removeChild(this)
  142. })
  143. }
  144. if (isPlainObject(properties)) {
  145. nodes = $(dom)
  146. $.each(properties, function(key, value) {
  147. if (methodAttributes.indexOf(key) > -1) nodes[key](value)
  148. else nodes.attr(key, value)
  149. })
  150. }
  151. return dom
  152. }
  153. // `$.zepto.Z` swaps out the prototype of the given `dom` array
  154. // of nodes with `$.fn` and thus supplying all the Zepto functions
  155. // to the array. This method can be overridden in plugins.
  156. zepto.Z = function(dom, selector) {
  157. return new Z(dom, selector)
  158. }
  159. // `$.zepto.isZ` should return `true` if the given object is a Zepto
  160. // collection. This method can be overridden in plugins.
  161. zepto.isZ = function(object) {
  162. return object instanceof zepto.Z
  163. }
  164. // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
  165. // takes a CSS selector and an optional context (and handles various
  166. // special cases).
  167. // This method can be overridden in plugins.
  168. zepto.init = function(selector, context) {
  169. var dom
  170. // If nothing given, return an empty Zepto collection
  171. if (!selector) return zepto.Z()
  172. // Optimize for string selectors
  173. else if (typeof selector == 'string') {
  174. selector = selector.trim()
  175. // If it's a html fragment, create nodes from it
  176. // Note: In both Chrome 21 and Firefox 15, DOM error 12
  177. // is thrown if the fragment doesn't begin with <
  178. if (selector[0] == '<' && fragmentRE.test(selector))
  179. dom = zepto.fragment(selector, RegExp.$1, context), selector = null
  180. // If there's a context, create a collection on that context first, and select
  181. // nodes from there
  182. else if (context !== undefined) return $(context).find(selector)
  183. // If it's a CSS selector, use it to select nodes.
  184. else dom = zepto.qsa(document, selector)
  185. }
  186. // If a function is given, call it when the DOM is ready
  187. else if (isFunction(selector)) return $(document).ready(selector)
  188. // If a Zepto collection is given, just return it
  189. else if (zepto.isZ(selector)) return selector
  190. else {
  191. // normalize array if an array of nodes is given
  192. if (isArray(selector)) dom = compact(selector)
  193. // Wrap DOM nodes.
  194. else if (isObject(selector))
  195. dom = [selector], selector = null
  196. // If it's a html fragment, create nodes from it
  197. else if (fragmentRE.test(selector))
  198. dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
  199. // If there's a context, create a collection on that context first, and select
  200. // nodes from there
  201. else if (context !== undefined) return $(context).find(selector)
  202. // And last but no least, if it's a CSS selector, use it to select nodes.
  203. else dom = zepto.qsa(document, selector)
  204. }
  205. // create a new Zepto collection from the nodes found
  206. return zepto.Z(dom, selector)
  207. }
  208. // `$` will be the base `Zepto` object. When calling this
  209. // function just call `$.zepto.init, which makes the implementation
  210. // details of selecting nodes and creating Zepto collections
  211. // patchable in plugins.
  212. $ = function(selector, context){
  213. return zepto.init(selector, context)
  214. }
  215. function extend(target, source, deep) {
  216. for (key in source)
  217. if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
  218. if (isPlainObject(source[key]) && !isPlainObject(target[key]))
  219. target[key] = {}
  220. if (isArray(source[key]) && !isArray(target[key]))
  221. target[key] = []
  222. extend(target[key], source[key], deep)
  223. }
  224. else if (source[key] !== undefined) target[key] = source[key]
  225. }
  226. // Copy all but undefined properties from one or more
  227. // objects to the `target` object.
  228. $.extend = function(target){
  229. var deep, args = slice.call(arguments, 1)
  230. if (typeof target == 'boolean') {
  231. deep = target
  232. target = args.shift()
  233. }
  234. args.forEach(function(arg){ extend(target, arg, deep) })
  235. return target
  236. }
  237. // `$.zepto.qsa` is Zepto's CSS selector implementation which
  238. // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
  239. // This method can be overridden in plugins.
  240. zepto.qsa = function(element, selector){
  241. var found,
  242. maybeID = selector[0] == '#',
  243. maybeClass = !maybeID && selector[0] == '.',
  244. nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
  245. isSimple = simpleSelectorRE.test(nameOnly)
  246. return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById
  247. ( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
  248. (element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] :
  249. slice.call(
  250. isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName
  251. maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
  252. element.getElementsByTagName(selector) : // Or a tag
  253. element.querySelectorAll(selector) // Or it's not simple, and we need to query all
  254. )
  255. }
  256. function filtered(nodes, selector) {
  257. return selector == null ? $(nodes) : $(nodes).filter(selector)
  258. }
  259. $.contains = document.documentElement.contains ?
  260. function(parent, node) {
  261. return parent !== node && parent.contains(node)
  262. } :
  263. function(parent, node) {
  264. while (node && (node = node.parentNode))
  265. if (node === parent) return true
  266. return false
  267. }
  268. function funcArg(context, arg, idx, payload) {
  269. return isFunction(arg) ? arg.call(context, idx, payload) : arg
  270. }
  271. function setAttribute(node, name, value) {
  272. value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
  273. }
  274. // access className property while respecting SVGAnimatedString
  275. function className(node, value){
  276. var klass = node.className || '',
  277. svg = klass && klass.baseVal !== undefined
  278. if (value === undefined) return svg ? klass.baseVal : klass
  279. svg ? (klass.baseVal = value) : (node.className = value)
  280. }
  281. // "true" => true
  282. // "false" => false
  283. // "null" => null
  284. // "42" => 42
  285. // "42.5" => 42.5
  286. // "08" => "08"
  287. // JSON => parse if valid
  288. // String => self
  289. function deserializeValue(value) {
  290. try {
  291. return value ?
  292. value == "true" ||
  293. ( value == "false" ? false :
  294. value == "null" ? null :
  295. +value + "" == value ? +value :
  296. /^[\[\{]/.test(value) ? $.parseJSON(value) :
  297. value )
  298. : value
  299. } catch(e) {
  300. return value
  301. }
  302. }
  303. $.type = type
  304. $.isFunction = isFunction
  305. $.isWindow = isWindow
  306. $.isArray = isArray
  307. $.isPlainObject = isPlainObject
  308. $.isEmptyObject = function(obj) {
  309. var name
  310. for (name in obj) return false
  311. return true
  312. }
  313. $.isNumeric = function(val) {
  314. var num = Number(val), type = typeof val
  315. return val != null && type != 'boolean' &&
  316. (type != 'string' || val.length) &&
  317. !isNaN(num) && isFinite(num) || false
  318. }
  319. $.inArray = function(elem, array, i){
  320. return emptyArray.indexOf.call(array, elem, i)
  321. }
  322. $.camelCase = camelize
  323. $.trim = function(str) {
  324. return str == null ? "" : String.prototype.trim.call(str)
  325. }
  326. // plugin compatibility
  327. $.uuid = 0
  328. $.support = { }
  329. $.expr = { }
  330. $.noop = function() {}
  331. $.map = function(elements, callback){
  332. var value, values = [], i, key
  333. if (likeArray(elements))
  334. for (i = 0; i < elements.length; i++) {
  335. value = callback(elements[i], i)
  336. if (value != null) values.push(value)
  337. }
  338. else
  339. for (key in elements) {
  340. value = callback(elements[key], key)
  341. if (value != null) values.push(value)
  342. }
  343. return flatten(values)
  344. }
  345. $.each = function(elements, callback){
  346. var i, key
  347. if (likeArray(elements)) {
  348. for (i = 0; i < elements.length; i++)
  349. if (callback.call(elements[i], i, elements[i]) === false) return elements
  350. } else {
  351. for (key in elements)
  352. if (callback.call(elements[key], key, elements[key]) === false) return elements
  353. }
  354. return elements
  355. }
  356. $.grep = function(elements, callback){
  357. return filter.call(elements, callback)
  358. }
  359. if (window.JSON) $.parseJSON = JSON.parse
  360. // Populate the class2type map
  361. $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
  362. class2type[ "[object " + name + "]" ] = name.toLowerCase()
  363. })
  364. // Define methods that will be available on all
  365. // Zepto collections
  366. $.fn = {
  367. constructor: zepto.Z,
  368. length: 0,
  369. // Because a collection acts like an array
  370. // copy over these useful array functions.
  371. forEach: emptyArray.forEach,
  372. reduce: emptyArray.reduce,
  373. push: emptyArray.push,
  374. sort: emptyArray.sort,
  375. splice: emptyArray.splice,
  376. indexOf: emptyArray.indexOf,
  377. concat: function(){
  378. var i, value, args = []
  379. for (i = 0; i < arguments.length; i++) {
  380. value = arguments[i]
  381. args[i] = zepto.isZ(value) ? value.toArray() : value
  382. }
  383. return concat.apply(zepto.isZ(this) ? this.toArray() : this, args)
  384. },
  385. // `map` and `slice` in the jQuery API work differently
  386. // from their array counterparts
  387. map: function(fn){
  388. return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
  389. },
  390. slice: function(){
  391. return $(slice.apply(this, arguments))
  392. },
  393. ready: function(callback){
  394. // need to check if document.body exists for IE as that browser reports
  395. // document ready when it hasn't yet created the body element
  396. if (readyRE.test(document.readyState) && document.body) callback($)
  397. else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
  398. return this
  399. },
  400. get: function(idx){
  401. return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
  402. },
  403. toArray: function(){ return this.get() },
  404. size: function(){
  405. return this.length
  406. },
  407. remove: function(){
  408. return this.each(function(){
  409. if (this.parentNode != null)
  410. this.parentNode.removeChild(this)
  411. })
  412. },
  413. each: function(callback){
  414. emptyArray.every.call(this, function(el, idx){
  415. return callback.call(el, idx, el) !== false
  416. })
  417. return this
  418. },
  419. filter: function(selector){
  420. if (isFunction(selector)) return this.not(this.not(selector))
  421. return $(filter.call(this, function(element){
  422. return zepto.matches(element, selector)
  423. }))
  424. },
  425. add: function(selector,context){
  426. return $(uniq(this.concat($(selector,context))))
  427. },
  428. is: function(selector){
  429. return this.length > 0 && zepto.matches(this[0], selector)
  430. },
  431. not: function(selector){
  432. var nodes=[]
  433. if (isFunction(selector) && selector.call !== undefined)
  434. this.each(function(idx){
  435. if (!selector.call(this,idx)) nodes.push(this)
  436. })
  437. else {
  438. var excludes = typeof selector == 'string' ? this.filter(selector) :
  439. (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
  440. this.forEach(function(el){
  441. if (excludes.indexOf(el) < 0) nodes.push(el)
  442. })
  443. }
  444. return $(nodes)
  445. },
  446. has: function(selector){
  447. return this.filter(function(){
  448. return isObject(selector) ?
  449. $.contains(this, selector) :
  450. $(this).find(selector).size()
  451. })
  452. },
  453. eq: function(idx){
  454. return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
  455. },
  456. first: function(){
  457. var el = this[0]
  458. return el && !isObject(el) ? el : $(el)
  459. },
  460. last: function(){
  461. var el = this[this.length - 1]
  462. return el && !isObject(el) ? el : $(el)
  463. },
  464. find: function(selector){
  465. var result, $this = this
  466. if (!selector) result = $()
  467. else if (typeof selector == 'object')
  468. result = $(selector).filter(function(){
  469. var node = this
  470. return emptyArray.some.call($this, function(parent){
  471. return $.contains(parent, node)
  472. })
  473. })
  474. else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
  475. else result = this.map(function(){ return zepto.qsa(this, selector) })
  476. return result
  477. },
  478. closest: function(selector, context){
  479. var nodes = [], collection = typeof selector == 'object' && $(selector)
  480. this.each(function(_, node){
  481. while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
  482. node = node !== context && !isDocument(node) && node.parentNode
  483. if (node && nodes.indexOf(node) < 0) nodes.push(node)
  484. })
  485. return $(nodes)
  486. },
  487. parents: function(selector){
  488. var ancestors = [], nodes = this
  489. while (nodes.length > 0)
  490. nodes = $.map(nodes, function(node){
  491. if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
  492. ancestors.push(node)
  493. return node
  494. }
  495. })
  496. return filtered(ancestors, selector)
  497. },
  498. parent: function(selector){
  499. return filtered(uniq(this.pluck('parentNode')), selector)
  500. },
  501. children: function(selector){
  502. return filtered(this.map(function(){ return children(this) }), selector)
  503. },
  504. contents: function() {
  505. return this.map(function() { return this.contentDocument || slice.call(this.childNodes) })
  506. },
  507. siblings: function(selector){
  508. return filtered(this.map(function(i, el){
  509. return filter.call(children(el.parentNode), function(child){ return child!==el })
  510. }), selector)
  511. },
  512. empty: function(){
  513. return this.each(function(){ this.innerHTML = '' })
  514. },
  515. // `pluck` is borrowed from Prototype.js
  516. pluck: function(property){
  517. return $.map(this, function(el){ return el[property] })
  518. },
  519. show: function(){
  520. return this.each(function(){
  521. this.style.display == "none" && (this.style.display = '')
  522. if (getComputedStyle(this, '').getPropertyValue("display") == "none")
  523. this.style.display = defaultDisplay(this.nodeName)
  524. })
  525. },
  526. replaceWith: function(newContent){
  527. return this.before(newContent).remove()
  528. },
  529. wrap: function(structure){
  530. var func = isFunction(structure)
  531. if (this[0] && !func)
  532. var dom = $(structure).get(0),
  533. clone = dom.parentNode || this.length > 1
  534. return this.each(function(index){
  535. $(this).wrapAll(
  536. func ? structure.call(this, index) :
  537. clone ? dom.cloneNode(true) : dom
  538. )
  539. })
  540. },
  541. wrapAll: function(structure){
  542. if (this[0]) {
  543. $(this[0]).before(structure = $(structure))
  544. var children
  545. // drill down to the inmost element
  546. while ((children = structure.children()).length) structure = children.first()
  547. $(structure).append(this)
  548. }
  549. return this
  550. },
  551. wrapInner: function(structure){
  552. var func = isFunction(structure)
  553. return this.each(function(index){
  554. var self = $(this), contents = self.contents(),
  555. dom = func ? structure.call(this, index) : structure
  556. contents.length ? contents.wrapAll(dom) : self.append(dom)
  557. })
  558. },
  559. unwrap: function(){
  560. this.parent().each(function(){
  561. $(this).replaceWith($(this).children())
  562. })
  563. return this
  564. },
  565. clone: function(){
  566. return this.map(function(){ return this.cloneNode(true) })
  567. },
  568. hide: function(){
  569. return this.css("display", "none")
  570. },
  571. toggle: function(setting){
  572. return this.each(function(){
  573. var el = $(this)
  574. ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
  575. })
  576. },
  577. prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
  578. next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
  579. html: function(html){
  580. return 0 in arguments ?
  581. this.each(function(idx){
  582. var originHtml = this.innerHTML
  583. $(this).empty().append( funcArg(this, html, idx, originHtml) )
  584. }) :
  585. (0 in this ? this[0].innerHTML : null)
  586. },
  587. text: function(text){
  588. return 0 in arguments ?
  589. this.each(function(idx){
  590. var newText = funcArg(this, text, idx, this.textContent)
  591. this.textContent = newText == null ? '' : ''+newText
  592. }) :
  593. (0 in this ? this.pluck('textContent').join("") : null)
  594. },
  595. attr: function(name, value){
  596. var result
  597. return (typeof name == 'string' && !(1 in arguments)) ?
  598. (0 in this && this[0].nodeType == 1 && (result = this[0].getAttribute(name)) != null ? result : undefined) :
  599. this.each(function(idx){
  600. if (this.nodeType !== 1) return
  601. if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
  602. else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
  603. })
  604. },
  605. removeAttr: function(name){
  606. return this.each(function(){ this.nodeType === 1 && name.split(' ').forEach(function(attribute){
  607. setAttribute(this, attribute)
  608. }, this)})
  609. },
  610. prop: function(name, value){
  611. name = propMap[name] || name
  612. return (1 in arguments) ?
  613. this.each(function(idx){
  614. this[name] = funcArg(this, value, idx, this[name])
  615. }) :
  616. (this[0] && this[0][name])
  617. },
  618. removeProp: function(name){
  619. name = propMap[name] || name
  620. return this.each(function(){ delete this[name] })
  621. },
  622. data: function(name, value){
  623. var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase()
  624. var data = (1 in arguments) ?
  625. this.attr(attrName, value) :
  626. this.attr(attrName)
  627. return data !== null ? deserializeValue(data) : undefined
  628. },
  629. val: function(value){
  630. if (0 in arguments) {
  631. if (value == null) value = ""
  632. return this.each(function(idx){
  633. this.value = funcArg(this, value, idx, this.value)
  634. })
  635. } else {
  636. return this[0] && (this[0].multiple ?
  637. $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
  638. this[0].value)
  639. }
  640. },
  641. offset: function(coordinates){
  642. if (coordinates) return this.each(function(index){
  643. var $this = $(this),
  644. coords = funcArg(this, coordinates, index, $this.offset()),
  645. parentOffset = $this.offsetParent().offset(),
  646. props = {
  647. top: coords.top - parentOffset.top,
  648. left: coords.left - parentOffset.left
  649. }
  650. if ($this.css('position') == 'static') props['position'] = 'relative'
  651. $this.css(props)
  652. })
  653. if (!this.length) return null
  654. if (document.documentElement !== this[0] && !$.contains(document.documentElement, this[0]))
  655. return {top: 0, left: 0}
  656. var obj = this[0].getBoundingClientRect()
  657. return {
  658. left: obj.left + window.pageXOffset,
  659. top: obj.top + window.pageYOffset,
  660. width: Math.round(obj.width),
  661. height: Math.round(obj.height)
  662. }
  663. },
  664. css: function(property, value){
  665. if (arguments.length < 2) {
  666. var element = this[0]
  667. if (typeof property == 'string') {
  668. if (!element) return
  669. return element.style[camelize(property)] || getComputedStyle(element, '').getPropertyValue(property)
  670. } else if (isArray(property)) {
  671. if (!element) return
  672. var props = {}
  673. var computedStyle = getComputedStyle(element, '')
  674. $.each(property, function(_, prop){
  675. props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
  676. })
  677. return props
  678. }
  679. }
  680. var css = ''
  681. if (type(property) == 'string') {
  682. if (!value && value !== 0)
  683. this.each(function(){ this.style.removeProperty(dasherize(property)) })
  684. else
  685. css = dasherize(property) + ":" + maybeAddPx(property, value)
  686. } else {
  687. for (key in property)
  688. if (!property[key] && property[key] !== 0)
  689. this.each(function(){ this.style.removeProperty(dasherize(key)) })
  690. else
  691. css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
  692. }
  693. return this.each(function(){ this.style.cssText += ';' + css })
  694. },
  695. index: function(element){
  696. return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
  697. },
  698. hasClass: function(name){
  699. if (!name) return false
  700. return emptyArray.some.call(this, function(el){
  701. return this.test(className(el))
  702. }, classRE(name))
  703. },
  704. addClass: function(name){
  705. if (!name) return this
  706. return this.each(function(idx){
  707. if (!('className' in this)) return
  708. classList = []
  709. var cls = className(this), newName = funcArg(this, name, idx, cls)
  710. newName.split(/\s+/g).forEach(function(klass){
  711. if (!$(this).hasClass(klass)) classList.push(klass)
  712. }, this)
  713. classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
  714. })
  715. },
  716. removeClass: function(name){
  717. return this.each(function(idx){
  718. if (!('className' in this)) return
  719. if (name === undefined) return className(this, '')
  720. classList = className(this)
  721. funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
  722. classList = classList.replace(classRE(klass), " ")
  723. })
  724. className(this, classList.trim())
  725. })
  726. },
  727. toggleClass: function(name, when){
  728. if (!name) return this
  729. return this.each(function(idx){
  730. var $this = $(this), names = funcArg(this, name, idx, className(this))
  731. names.split(/\s+/g).forEach(function(klass){
  732. (when === undefined ? !$this.hasClass(klass) : when) ?
  733. $this.addClass(klass) : $this.removeClass(klass)
  734. })
  735. })
  736. },
  737. scrollTop: function(value){
  738. if (!this.length) return
  739. var hasScrollTop = 'scrollTop' in this[0]
  740. if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
  741. return this.each(hasScrollTop ?
  742. function(){ this.scrollTop = value } :
  743. function(){ this.scrollTo(this.scrollX, value) })
  744. },
  745. scrollLeft: function(value){
  746. if (!this.length) return
  747. var hasScrollLeft = 'scrollLeft' in this[0]
  748. if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset
  749. return this.each(hasScrollLeft ?
  750. function(){ this.scrollLeft = value } :
  751. function(){ this.scrollTo(value, this.scrollY) })
  752. },
  753. position: function() {
  754. if (!this.length) return
  755. var elem = this[0],
  756. // Get *real* offsetParent
  757. offsetParent = this.offsetParent(),
  758. // Get correct offsets
  759. offset = this.offset(),
  760. parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset()
  761. // Subtract element margins
  762. // note: when an element has margin: auto the offsetLeft and marginLeft
  763. // are the same in Safari causing offset.left to incorrectly be 0
  764. offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
  765. offset.left -= parseFloat( $(elem).css('margin-left') ) || 0
  766. // Add offsetParent borders
  767. parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0
  768. parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0
  769. // Subtract the two offsets
  770. return {
  771. top: offset.top - parentOffset.top,
  772. left: offset.left - parentOffset.left
  773. }
  774. },
  775. offsetParent: function() {
  776. return this.map(function(){
  777. var parent = this.offsetParent || document.body
  778. while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
  779. parent = parent.offsetParent
  780. return parent
  781. })
  782. }
  783. }
  784. // for now
  785. $.fn.detach = $.fn.remove
  786. // Generate the `width` and `height` functions
  787. ;['width', 'height'].forEach(function(dimension){
  788. var dimensionProperty =
  789. dimension.replace(/./, function(m){ return m[0].toUpperCase() })
  790. $.fn[dimension] = function(value){
  791. var offset, el = this[0]
  792. if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
  793. isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
  794. (offset = this.offset()) && offset[dimension]
  795. else return this.each(function(idx){
  796. el = $(this)
  797. el.css(dimension, funcArg(this, value, idx, el[dimension]()))
  798. })
  799. }
  800. })
  801. function traverseNode(node, fun) {
  802. fun(node)
  803. for (var i = 0, len = node.childNodes.length; i < len; i++)
  804. traverseNode(node.childNodes[i], fun)
  805. }
  806. // Generate the `after`, `prepend`, `before`, `append`,
  807. // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
  808. adjacencyOperators.forEach(function(operator, operatorIndex) {
  809. var inside = operatorIndex % 2 //=> prepend, append
  810. $.fn[operator] = function(){
  811. // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
  812. var argType, nodes = $.map(arguments, function(arg) {
  813. var arr = []
  814. argType = type(arg)
  815. if (argType == "array") {
  816. arg.forEach(function(el) {
  817. if (el.nodeType !== undefined) return arr.push(el)
  818. else if ($.zepto.isZ(el)) return arr = arr.concat(el.get())
  819. arr = arr.concat(zepto.fragment(el))
  820. })
  821. return arr
  822. }
  823. return argType == "object" || arg == null ?
  824. arg : zepto.fragment(arg)
  825. }),
  826. parent, copyByClone = this.length > 1
  827. if (nodes.length < 1) return this
  828. return this.each(function(_, target){
  829. parent = inside ? target : target.parentNode
  830. // convert all methods to a "before" operation
  831. target = operatorIndex == 0 ? target.nextSibling :
  832. operatorIndex == 1 ? target.firstChild :
  833. operatorIndex == 2 ? target :
  834. null
  835. var parentInDocument = $.contains(document.documentElement, parent)
  836. nodes.forEach(function(node){
  837. if (copyByClone) node = node.cloneNode(true)
  838. else if (!parent) return $(node).remove()
  839. parent.insertBefore(node, target)
  840. if (parentInDocument) traverseNode(node, function(el){
  841. if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
  842. (!el.type || el.type === 'text/javascript') && !el.src){
  843. var target = el.ownerDocument ? el.ownerDocument.defaultView : window
  844. target['eval'].call(target, el.innerHTML)
  845. }
  846. })
  847. })
  848. })
  849. }
  850. // after => insertAfter
  851. // prepend => prependTo
  852. // before => insertBefore
  853. // append => appendTo
  854. $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
  855. $(html)[operator](this)
  856. return this
  857. }
  858. })
  859. zepto.Z.prototype = Z.prototype = $.fn
  860. // Export internal API functions in the `$.zepto` namespace
  861. zepto.uniq = uniq
  862. zepto.deserializeValue = deserializeValue
  863. $.zepto = zepto
  864. return $
  865. })()
  866. window.Zepto = Zepto
  867. window.$ === undefined && (window.$ = Zepto)
  868. ;(function($){
  869. var _zid = 1, undefined,
  870. slice = Array.prototype.slice,
  871. isFunction = $.isFunction,
  872. isString = function(obj){ return typeof obj == 'string' },
  873. handlers = {},
  874. specialEvents={},
  875. focusinSupported = 'onfocusin' in window,
  876. focus = { focus: 'focusin', blur: 'focusout' },
  877. hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }
  878. specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'
  879. function zid(element) {
  880. return element._zid || (element._zid = _zid++)
  881. }
  882. function findHandlers(element, event, fn, selector) {
  883. event = parse(event)
  884. if (event.ns) var matcher = matcherFor(event.ns)
  885. return (handlers[zid(element)] || []).filter(function(handler) {
  886. return handler
  887. && (!event.e || handler.e == event.e)
  888. && (!event.ns || matcher.test(handler.ns))
  889. && (!fn || zid(handler.fn) === zid(fn))
  890. && (!selector || handler.sel == selector)
  891. })
  892. }
  893. function parse(event) {
  894. var parts = ('' + event).split('.')
  895. return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
  896. }
  897. function matcherFor(ns) {
  898. return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
  899. }
  900. function eventCapture(handler, captureSetting) {
  901. return handler.del &&
  902. (!focusinSupported && (handler.e in focus)) ||
  903. !!captureSetting
  904. }
  905. function realEvent(type) {
  906. return hover[type] || (focusinSupported && focus[type]) || type
  907. }
  908. function add(element, events, fn, data, selector, delegator, capture){
  909. var id = zid(element), set = (handlers[id] || (handlers[id] = []))
  910. events.split(/\s/).forEach(function(event){
  911. if (event == 'ready') return $(document).ready(fn)
  912. var handler = parse(event)
  913. handler.fn = fn
  914. handler.sel = selector
  915. // emulate mouseenter, mouseleave
  916. if (handler.e in hover) fn = function(e){
  917. var related = e.relatedTarget
  918. if (!related || (related !== this && !$.contains(this, related)))
  919. return handler.fn.apply(this, arguments)
  920. }
  921. handler.del = delegator
  922. var callback = delegator || fn
  923. handler.proxy = function(e){
  924. e = compatible(e)
  925. if (e.isImmediatePropagationStopped()) return
  926. e.data = data
  927. var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args))
  928. if (result === false) e.preventDefault(), e.stopPropagation()
  929. return result
  930. }
  931. handler.i = set.length
  932. set.push(handler)
  933. if ('addEventListener' in element)
  934. element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
  935. })
  936. }
  937. function remove(element, events, fn, selector, capture){
  938. var id = zid(element)
  939. ;(events || '').split(/\s/).forEach(function(event){
  940. findHandlers(element, event, fn, selector).forEach(function(handler){
  941. delete handlers[id][handler.i]
  942. if ('removeEventListener' in element)
  943. element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
  944. })
  945. })
  946. }
  947. $.event = { add: add, remove: remove }
  948. $.proxy = function(fn, context) {
  949. var args = (2 in arguments) && slice.call(arguments, 2)
  950. if (isFunction(fn)) {
  951. var proxyFn = function(){ return fn.apply(context, args ? args.concat(slice.call(arguments)) : arguments) }
  952. proxyFn._zid = zid(fn)
  953. return proxyFn
  954. } else if (isString(context)) {
  955. if (args) {
  956. args.unshift(fn[context], fn)
  957. return $.proxy.apply(null, args)
  958. } else {
  959. return $.proxy(fn[context], fn)
  960. }
  961. } else {
  962. throw new TypeError("expected function")
  963. }
  964. }
  965. $.fn.bind = function(event, data, callback){
  966. return this.on(event, data, callback)
  967. }
  968. $.fn.unbind = function(event, callback){
  969. return this.off(event, callback)
  970. }
  971. $.fn.one = function(event, selector, data, callback){
  972. return this.on(event, selector, data, callback, 1)
  973. }
  974. var returnTrue = function(){return true},
  975. returnFalse = function(){return false},
  976. ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/,
  977. eventMethods = {
  978. preventDefault: 'isDefaultPrevented',
  979. stopImmediatePropagation: 'isImmediatePropagationStopped',
  980. stopPropagation: 'isPropagationStopped'
  981. }
  982. function compatible(event, source) {
  983. if (source || !event.isDefaultPrevented) {
  984. source || (source = event)
  985. $.each(eventMethods, function(name, predicate) {
  986. var sourceMethod = source[name]
  987. event[name] = function(){
  988. this[predicate] = returnTrue
  989. return sourceMethod && sourceMethod.apply(source, arguments)
  990. }
  991. event[predicate] = returnFalse
  992. })
  993. event.timeStamp || (event.timeStamp = Date.now())
  994. if (source.defaultPrevented !== undefined ? source.defaultPrevented :
  995. 'returnValue' in source ? source.returnValue === false :
  996. source.getPreventDefault && source.getPreventDefault())
  997. event.isDefaultPrevented = returnTrue
  998. }
  999. return event
  1000. }
  1001. function createProxy(event) {
  1002. var key, proxy = { originalEvent: event }
  1003. for (key in event)
  1004. if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key]
  1005. return compatible(proxy, event)
  1006. }
  1007. $.fn.delegate = function(selector, event, callback){
  1008. return this.on(event, selector, callback)
  1009. }
  1010. $.fn.undelegate = function(selector, event, callback){
  1011. return this.off(event, selector, callback)
  1012. }
  1013. $.fn.live = function(event, callback){
  1014. $(document.body).delegate(this.selector, event, callback)
  1015. return this
  1016. }
  1017. $.fn.die = function(event, callback){
  1018. $(document.body).undelegate(this.selector, event, callback)
  1019. return this
  1020. }
  1021. $.fn.on = function(event, selector, data, callback, one){
  1022. var autoRemove, delegator, $this = this
  1023. if (event && !isString(event)) {
  1024. $.each(event, function(type, fn){
  1025. $this.on(type, selector, data, fn, one)
  1026. })
  1027. return $this
  1028. }
  1029. if (!isString(selector) && !isFunction(callback) && callback !== false)
  1030. callback = data, data = selector, selector = undefined
  1031. if (callback === undefined || data === false)
  1032. callback = data, data = undefined
  1033. if (callback === false) callback = returnFalse
  1034. return $this.each(function(_, element){
  1035. if (one) autoRemove = function(e){
  1036. remove(element, e.type, callback)
  1037. return callback.apply(this, arguments)
  1038. }
  1039. if (selector) delegator = function(e){
  1040. var evt, match = $(e.target).closest(selector, element).get(0)
  1041. if (match && match !== element) {
  1042. evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
  1043. return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
  1044. }
  1045. }
  1046. add(element, event, callback, data, selector, delegator || autoRemove)
  1047. })
  1048. }
  1049. $.fn.off = function(event, selector, callback){
  1050. var $this = this
  1051. if (event && !isString(event)) {
  1052. $.each(event, function(type, fn){
  1053. $this.off(type, selector, fn)
  1054. })
  1055. return $this
  1056. }
  1057. if (!isString(selector) && !isFunction(callback) && callback !== false)
  1058. callback = selector, selector = undefined
  1059. if (callback === false) callback = returnFalse
  1060. return $this.each(function(){
  1061. remove(this, event, callback, selector)
  1062. })
  1063. }
  1064. $.fn.trigger = function(event, args){
  1065. event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event)
  1066. event._args = args
  1067. return this.each(function(){
  1068. // handle focus(), blur() by calling them directly
  1069. if (event.type in focus && typeof this[event.type] == "function") this[event.type]()
  1070. // items in the collection might not be DOM elements
  1071. else if ('dispatchEvent' in this) this.dispatchEvent(event)
  1072. else $(this).triggerHandler(event, args)
  1073. })
  1074. }
  1075. // triggers event handlers on current element just as if an event occurred,
  1076. // doesn't trigger an actual event, doesn't bubble
  1077. $.fn.triggerHandler = function(event, args){
  1078. var e, result
  1079. this.each(function(i, element){
  1080. e = createProxy(isString(event) ? $.Event(event) : event)
  1081. e._args = args
  1082. e.target = element
  1083. $.each(findHandlers(element, event.type || event), function(i, handler){
  1084. result = handler.proxy(e)
  1085. if (e.isImmediatePropagationStopped()) return false
  1086. })
  1087. })
  1088. return result
  1089. }
  1090. // shortcut methods for `.bind(event, fn)` for each event type
  1091. ;('focusin focusout focus blur load resize scroll unload click dblclick '+
  1092. 'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+
  1093. 'change select keydown keypress keyup error').split(' ').forEach(function(event) {
  1094. $.fn[event] = function(callback) {
  1095. return (0 in arguments) ?
  1096. this.bind(event, callback) :
  1097. this.trigger(event)
  1098. }
  1099. })
  1100. $.Event = function(type, props) {
  1101. if (!isString(type)) props = type, type = props.type
  1102. var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
  1103. if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
  1104. event.initEvent(type, bubbles, true)
  1105. return compatible(event)
  1106. }
  1107. })(Zepto)
  1108. ;(function($){
  1109. var jsonpID = +new Date(),
  1110. document = window.document,
  1111. key,
  1112. name,
  1113. rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
  1114. scriptTypeRE = /^(?:text|application)\/javascript/i,
  1115. xmlTypeRE = /^(?:text|application)\/xml/i,
  1116. jsonType = 'application/json',
  1117. htmlType = 'text/html',
  1118. blankRE = /^\s*$/,
  1119. originAnchor = document.createElement('a')
  1120. originAnchor.href = window.location.href
  1121. // trigger a custom event and return false if it was cancelled
  1122. function triggerAndReturn(context, eventName, data) {
  1123. var event = $.Event(eventName)
  1124. $(context).trigger(event, data)
  1125. return !event.isDefaultPrevented()
  1126. }
  1127. // trigger an Ajax "global" event
  1128. function triggerGlobal(settings, context, eventName, data) {
  1129. if (settings.global) return triggerAndReturn(context || document, eventName, data)
  1130. }
  1131. // Number of active Ajax requests
  1132. $.active = 0
  1133. function ajaxStart(settings) {
  1134. if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
  1135. }
  1136. function ajaxStop(settings) {
  1137. if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop')
  1138. }
  1139. // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
  1140. function ajaxBeforeSend(xhr, settings) {
  1141. var context = settings.context
  1142. if (settings.beforeSend.call(context, xhr, settings) === false ||
  1143. triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
  1144. return false
  1145. triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
  1146. }
  1147. function ajaxSuccess(data, xhr, settings, deferred) {
  1148. var context = settings.context, status = 'success'
  1149. settings.success.call(context, data, status, xhr)
  1150. if (deferred) deferred.resolveWith(context, [data, status, xhr])
  1151. triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
  1152. ajaxComplete(status, xhr, settings)
  1153. }
  1154. // type: "timeout", "error", "abort", "parsererror"
  1155. function ajaxError(error, type, xhr, settings, deferred) {
  1156. var context = settings.context
  1157. settings.error.call(context, xhr, type, error)
  1158. if (deferred) deferred.rejectWith(context, [xhr, type, error])
  1159. triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type])
  1160. ajaxComplete(type, xhr, settings)
  1161. }
  1162. // status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
  1163. function ajaxComplete(status, xhr, settings) {
  1164. var context = settings.context
  1165. settings.complete.call(context, xhr, status)
  1166. triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
  1167. ajaxStop(settings)
  1168. }
  1169. function ajaxDataFilter(data, type, settings) {
  1170. if (settings.dataFilter == empty) return data
  1171. var context = settings.context
  1172. return settings.dataFilter.call(context, data, type)
  1173. }
  1174. // Empty function, used as default callback
  1175. function empty() {}
  1176. $.ajaxJSONP = function(options, deferred){
  1177. if (!('type' in options)) return $.ajax(options)
  1178. var _callbackName = options.jsonpCallback,
  1179. callbackName = ($.isFunction(_callbackName) ?
  1180. _callbackName() : _callbackName) || ('Zepto' + (jsonpID++)),
  1181. script = document.createElement('script'),
  1182. originalCallback = window[callbackName],
  1183. responseData,
  1184. abort = function(errorType) {
  1185. $(script).triggerHandler('error', errorType || 'abort')
  1186. },
  1187. xhr = { abort: abort }, abortTimeout
  1188. if (deferred) deferred.promise(xhr)
  1189. $(script).on('load error', function(e, errorType){
  1190. clearTimeout(abortTimeout)
  1191. $(script).off().remove()
  1192. if (e.type == 'error' || !responseData) {
  1193. ajaxError(null, errorType || 'error', xhr, options, deferred)
  1194. } else {
  1195. ajaxSuccess(responseData[0], xhr, options, deferred)
  1196. }
  1197. window[callbackName] = originalCallback
  1198. if (responseData && $.isFunction(originalCallback))
  1199. originalCallback(responseData[0])
  1200. originalCallback = responseData = undefined
  1201. })
  1202. if (ajaxBeforeSend(xhr, options) === false) {
  1203. abort('abort')
  1204. return xhr
  1205. }
  1206. window[callbackName] = function(){
  1207. responseData = arguments
  1208. }
  1209. script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName)
  1210. document.head.appendChild(script)
  1211. if (options.timeout > 0) abortTimeout = setTimeout(function(){
  1212. abort('timeout')
  1213. }, options.timeout)
  1214. return xhr
  1215. }
  1216. $.ajaxSettings = {
  1217. // Default type of request
  1218. type: 'GET',
  1219. // Callback that is executed before request
  1220. beforeSend: empty,
  1221. // Callback that is executed if the request succeeds
  1222. success: empty,
  1223. // Callback that is executed the the server drops error
  1224. error: empty,
  1225. // Callback that is executed on request complete (both: error and success)
  1226. complete: empty,
  1227. // The context for the callbacks
  1228. context: null,
  1229. // Whether to trigger "global" Ajax events
  1230. global: true,
  1231. // Transport
  1232. xhr: function () {
  1233. return new window.XMLHttpRequest()
  1234. },
  1235. // MIME types mapping
  1236. // IIS returns Javascript as "application/x-javascript"
  1237. accepts: {
  1238. script: 'text/javascript, application/javascript, application/x-javascript',
  1239. json: jsonType,
  1240. xml: 'application/xml, text/xml',
  1241. html: htmlType,
  1242. text: 'text/plain'
  1243. },
  1244. // Whether the request is to another domain
  1245. crossDomain: false,
  1246. // Default timeout
  1247. timeout: 0,
  1248. // Whether data should be serialized to string
  1249. processData: true,
  1250. // Whether the browser should be allowed to cache GET responses
  1251. cache: true,
  1252. //Used to handle the raw response data of XMLHttpRequest.
  1253. //This is a pre-filtering function to sanitize the response.
  1254. //The sanitized response should be returned
  1255. dataFilter: empty
  1256. }
  1257. function mimeToDataType(mime) {
  1258. if (mime) mime = mime.split(';', 2)[0]
  1259. return mime && ( mime == htmlType ? 'html' :
  1260. mime == jsonType ? 'json' :
  1261. scriptTypeRE.test(mime) ? 'script' :
  1262. xmlTypeRE.test(mime) && 'xml' ) || 'text'
  1263. }
  1264. function appendQuery(url, query) {
  1265. if (query == '') return url
  1266. return (url + '&' + query).replace(/[&?]{1,2}/, '?')
  1267. }
  1268. // serialize payload and append it to the URL for GET requests
  1269. function serializeData(options) {
  1270. if (options.processData && options.data && $.type(options.data) != "string")
  1271. options.data = $.param(options.data, options.traditional)
  1272. if (options.data && (!options.type || options.type.toUpperCase() == 'GET' || 'jsonp' == options.dataType))
  1273. options.url = appendQuery(options.url, options.data), options.data = undefined
  1274. }
  1275. $.ajax = function(options){
  1276. var settings = $.extend({}, options || {}),
  1277. deferred = $.Deferred && $.Deferred(),
  1278. urlAnchor, hashIndex
  1279. for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]
  1280. ajaxStart(settings)
  1281. if (!settings.crossDomain) {
  1282. urlAnchor = document.createElement('a')
  1283. urlAnchor.href = settings.url
  1284. // cleans up URL for .href (IE only), see https://github.com/madrobby/zepto/pull/1049
  1285. urlAnchor.href = urlAnchor.href
  1286. settings.crossDomain = (originAnchor.protocol + '//' + originAnchor.host) !== (urlAnchor.protocol + '//' + urlAnchor.host)
  1287. }
  1288. if (!settings.url) settings.url = window.location.toString()
  1289. if ((hashIndex = settings.url.indexOf('#')) > -1) settings.url = settings.url.slice(0, hashIndex)
  1290. serializeData(settings)
  1291. var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url)
  1292. if (hasPlaceholder) dataType = 'jsonp'
  1293. if (settings.cache === false || (
  1294. (!options || options.cache !== true) &&
  1295. ('script' == dataType || 'jsonp' == dataType)
  1296. ))
  1297. settings.url = appendQuery(settings.url, '_=' + Date.now())
  1298. if ('jsonp' == dataType) {
  1299. if (!hasPlaceholder)
  1300. settings.url = appendQuery(settings.url,
  1301. settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?')
  1302. return $.ajaxJSONP(settings, deferred)
  1303. }
  1304. var mime = settings.accepts[dataType],
  1305. headers = { },
  1306. setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] },
  1307. protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
  1308. xhr = settings.xhr(),
  1309. nativeSetHeader = xhr.setRequestHeader,
  1310. abortTimeout
  1311. if (deferred) deferred.promise(xhr)
  1312. if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest')
  1313. setHeader('Accept', mime || '*/*')
  1314. if (mime = settings.mimeType || mime) {
  1315. if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
  1316. xhr.overrideMimeType && xhr.overrideMimeType(mime)
  1317. }
  1318. if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
  1319. setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded')
  1320. if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name])
  1321. xhr.setRequestHeader = setHeader
  1322. xhr.onreadystatechange = function(){
  1323. if (xhr.readyState == 4) {
  1324. xhr.onreadystatechange = empty
  1325. clearTimeout(abortTimeout)
  1326. var result, error = false
  1327. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
  1328. dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'))
  1329. if (xhr.responseType == 'arraybuffer' || xhr.responseType == 'blob')
  1330. result = xhr.response
  1331. else {
  1332. result = xhr.responseText
  1333. try {
  1334. // http://perfectionkills.com/global-eval-what-are-the-options/
  1335. // sanitize response accordingly if data filter callback provided
  1336. result = ajaxDataFilter(result, dataType, settings)
  1337. if (dataType == 'script') (1,eval)(result)
  1338. else if (dataType == 'xml') result = xhr.responseXML
  1339. else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
  1340. } catch (e) { error = e }
  1341. if (error) return ajaxError(error, 'parsererror', xhr, settings, deferred)
  1342. }
  1343. ajaxSuccess(result, xhr, settings, deferred)
  1344. } else {
  1345. ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred)
  1346. }
  1347. }
  1348. }
  1349. if (ajaxBeforeSend(xhr, settings) === false) {
  1350. xhr.abort()
  1351. ajaxError(null, 'abort', xhr, settings, deferred)
  1352. return xhr
  1353. }
  1354. var async = 'async' in settings ? settings.async : true
  1355. xhr.open(settings.type, settings.url, async, settings.username, settings.password)
  1356. if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name]
  1357. for (name in headers) nativeSetHeader.apply(xhr, headers[name])
  1358. if (settings.timeout > 0) abortTimeout = setTimeout(function(){
  1359. xhr.onreadystatechange = empty
  1360. xhr.abort()
  1361. ajaxError(null, 'timeout', xhr, settings, deferred)
  1362. }, settings.timeout)
  1363. // avoid sending empty string (#319)
  1364. xhr.send(settings.data ? settings.data : null)
  1365. return xhr
  1366. }
  1367. // handle optional data/success arguments
  1368. function parseArguments(url, data, success, dataType) {
  1369. if ($.isFunction(data)) dataType = success, success = data, data = undefined
  1370. if (!$.isFunction(success)) dataType = success, success = undefined
  1371. return {
  1372. url: url
  1373. , data: data
  1374. , success: success
  1375. , dataType: dataType
  1376. }
  1377. }
  1378. $.get = function(/* url, data, success, dataType */){
  1379. return $.ajax(parseArguments.apply(null, arguments))
  1380. }
  1381. $.post = function(/* url, data, success, dataType */){
  1382. var options = parseArguments.apply(null, arguments)
  1383. options.type = 'POST'
  1384. return $.ajax(options)
  1385. }
  1386. $.getJSON = function(/* url, data, success */){
  1387. var options = parseArguments.apply(null, arguments)
  1388. options.dataType = 'json'
  1389. return $.ajax(options)
  1390. }
  1391. $.fn.load = function(url, data, success){
  1392. if (!this.length) return this
  1393. var self = this, parts = url.split(/\s/), selector,
  1394. options = parseArguments(url, data, success),
  1395. callback = options.success
  1396. if (parts.length > 1) options.url = parts[0], selector = parts[1]
  1397. options.success = function(response){
  1398. self.html(selector ?
  1399. $('<div>').html(response.replace(rscript, "")).find(selector)
  1400. : response)
  1401. callback && callback.apply(self, arguments)
  1402. }
  1403. $.ajax(options)
  1404. return this
  1405. }
  1406. var escape = encodeURIComponent
  1407. function serialize(params, obj, traditional, scope){
  1408. var type, array = $.isArray(obj), hash = $.isPlainObject(obj)
  1409. $.each(obj, function(key, value) {
  1410. type = $.type(value)
  1411. if (scope) key = traditional ? scope :
  1412. scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']'
  1413. // handle data in serializeArray() format
  1414. if (!scope && array) params.add(value.name, value.value)
  1415. // recurse into nested objects
  1416. else if (type == "array" || (!traditional && type == "object"))
  1417. serialize(params, value, traditional, key)
  1418. else params.add(key, value)
  1419. })
  1420. }
  1421. $.param = function(obj, traditional){
  1422. var params = []
  1423. params.add = function(key, value) {
  1424. if ($.isFunction(value)) value = value()
  1425. if (value == null) value = ""
  1426. this.push(escape(key) + '=' + escape(value))
  1427. }
  1428. serialize(params, obj, traditional)
  1429. return params.join('&').replace(/%20/g, '+')
  1430. }
  1431. })(Zepto)
  1432. ;(function($){
  1433. $.fn.serializeArray = function() {
  1434. var name, type, result = [],
  1435. add = function(value) {
  1436. if (value.forEach) return value.forEach(add)
  1437. result.push({ name: name, value: value })
  1438. }
  1439. if (this[0]) $.each(this[0].elements, function(_, field){
  1440. type = field.type, name = field.name
  1441. if (name && field.nodeName.toLowerCase() != 'fieldset' &&
  1442. !field.disabled && type != 'submit' && type != 'reset' && type != 'button' && type != 'file' &&
  1443. ((type != 'radio' && type != 'checkbox') || field.checked))
  1444. add($(field).val())
  1445. })
  1446. return result
  1447. }
  1448. $.fn.serialize = function(){
  1449. var result = []
  1450. this.serializeArray().forEach(function(elm){
  1451. result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
  1452. })
  1453. return result.join('&')
  1454. }
  1455. $.fn.submit = function(callback) {
  1456. if (0 in arguments) this.bind('submit', callback)
  1457. else if (this.length) {
  1458. var event = $.Event('submit')
  1459. this.eq(0).trigger(event)
  1460. if (!event.isDefaultPrevented()) this.get(0).submit()
  1461. }
  1462. return this
  1463. }
  1464. })(Zepto)
  1465. ;(function(){
  1466. // getComputedStyle shouldn't freak out when called
  1467. // without a valid element as argument
  1468. try {
  1469. getComputedStyle(undefined)
  1470. } catch(e) {
  1471. var nativeGetComputedStyle = getComputedStyle
  1472. window.getComputedStyle = function(element, pseudoElement){
  1473. try {
  1474. return nativeGetComputedStyle(element, pseudoElement)
  1475. } catch(e) {
  1476. return null
  1477. }
  1478. }
  1479. }
  1480. })()
  1481. return Zepto
  1482. }))