zepto.js 57 KB

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