zepto.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. // Zepto.js
  2. // (c) 2010-2016 Thomas Fuchs
  3. // Zepto.js may be freely distributed under the MIT license.
  4. var Zepto = (function() {
  5. var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice,
  6. document = window.document,
  7. elementDisplay = {}, classCache = {},
  8. cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
  9. fragmentRE = /^\s*<(\w+|!)[^>]*>/,
  10. singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
  11. tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
  12. rootNodeRE = /^(?:body|html)$/i,
  13. capitalRE = /([A-Z])/g,
  14. // special attributes that should be get/set via method calls
  15. methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
  16. adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
  17. table = document.createElement('table'),
  18. tableRow = document.createElement('tr'),
  19. containers = {
  20. 'tr': document.createElement('tbody'),
  21. 'tbody': table, 'thead': table, 'tfoot': table,
  22. 'td': tableRow, 'th': tableRow,
  23. '*': document.createElement('div')
  24. },
  25. readyRE = /complete|loaded|interactive/,
  26. simpleSelectorRE = /^[\w-]*$/,
  27. class2type = {},
  28. toString = class2type.toString,
  29. zepto = {},
  30. camelize, uniq,
  31. tempParent = document.createElement('div'),
  32. propMap = {
  33. 'tabindex': 'tabIndex',
  34. 'readonly': 'readOnly',
  35. 'for': 'htmlFor',
  36. 'class': 'className',
  37. 'maxlength': 'maxLength',
  38. 'cellspacing': 'cellSpacing',
  39. 'cellpadding': 'cellPadding',
  40. 'rowspan': 'rowSpan',
  41. 'colspan': 'colSpan',
  42. 'usemap': 'useMap',
  43. 'frameborder': 'frameBorder',
  44. 'contenteditable': 'contentEditable'
  45. },
  46. isArray = Array.isArray ||
  47. function(object){ return object instanceof Array }
  48. zepto.matches = function(element, selector) {
  49. if (!selector || !element || element.nodeType !== 1) return false
  50. var matchesSelector = element.matches || element.webkitMatchesSelector ||
  51. element.mozMatchesSelector || element.oMatchesSelector ||
  52. element.matchesSelector
  53. if (matchesSelector) return matchesSelector.call(element, selector)
  54. // fall back to performing a selector:
  55. var match, parent = element.parentNode, temp = !parent
  56. if (temp) (parent = tempParent).appendChild(element)
  57. match = ~zepto.qsa(parent, selector).indexOf(element)
  58. temp && tempParent.removeChild(element)
  59. return match
  60. }
  61. function type(obj) {
  62. return obj == null ? String(obj) :
  63. class2type[toString.call(obj)] || "object"
  64. }
  65. function isFunction(value) { return type(value) == "function" }
  66. function isWindow(obj) { return obj != null && obj == obj.window }
  67. function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
  68. function isObject(obj) { return type(obj) == "object" }
  69. function isPlainObject(obj) {
  70. return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
  71. }
  72. function likeArray(obj) {
  73. var length = !!obj && 'length' in obj && obj.length,
  74. type = $.type(obj)
  75. return 'function' != type && !isWindow(obj) && (
  76. 'array' == type || length === 0 ||
  77. (typeof length == 'number' && length > 0 && (length - 1) in obj)
  78. )
  79. }
  80. function compact(array) { return filter.call(array, function(item){ return item != null }) }
  81. function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
  82. camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
  83. function dasherize(str) {
  84. return str.replace(/::/g, '/')
  85. .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
  86. .replace(/([a-z\d])([A-Z])/g, '$1_$2')
  87. .replace(/_/g, '-')
  88. .toLowerCase()
  89. }
  90. uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
  91. function classRE(name) {
  92. return name in classCache ?
  93. classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
  94. }
  95. function maybeAddPx(name, value) {
  96. return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
  97. }
  98. function defaultDisplay(nodeName) {
  99. var element, display
  100. if (!elementDisplay[nodeName]) {
  101. element = document.createElement(nodeName)
  102. document.body.appendChild(element)
  103. display = getComputedStyle(element, '').getPropertyValue("display")
  104. element.parentNode.removeChild(element)
  105. display == "none" && (display = "block")
  106. elementDisplay[nodeName] = display
  107. }
  108. return elementDisplay[nodeName]
  109. }
  110. function children(element) {
  111. return 'children' in element ?
  112. slice.call(element.children) :
  113. $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
  114. }
  115. function Z(dom, selector) {
  116. var i, len = dom ? dom.length : 0
  117. for (i = 0; i < len; i++) this[i] = dom[i]
  118. this.length = len
  119. this.selector = selector || ''
  120. }
  121. // `$.zepto.fragment` takes a html string and an optional tag name
  122. // to generate DOM nodes from the given html string.
  123. // The generated DOM nodes are returned as an array.
  124. // This function can be overridden in plugins for example to make
  125. // it compatible with browsers that don't support the DOM fully.
  126. zepto.fragment = function(html, name, properties) {
  127. var dom, nodes, container
  128. // A special case optimization for a single tag
  129. if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
  130. if (!dom) {
  131. if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
  132. if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
  133. if (!(name in containers)) name = '*'
  134. container = containers[name]
  135. container.innerHTML = '' + html
  136. dom = $.each(slice.call(container.childNodes), function(){
  137. container.removeChild(this)
  138. })
  139. }
  140. if (isPlainObject(properties)) {
  141. nodes = $(dom)
  142. $.each(properties, function(key, value) {
  143. if (methodAttributes.indexOf(key) > -1) nodes[key](value)
  144. else nodes.attr(key, value)
  145. })
  146. }
  147. return dom
  148. }
  149. // `$.zepto.Z` swaps out the prototype of the given `dom` array
  150. // of nodes with `$.fn` and thus supplying all the Zepto functions
  151. // to the array. This method can be overridden in plugins.
  152. zepto.Z = function(dom, selector) {
  153. return new Z(dom, selector)
  154. }
  155. // `$.zepto.isZ` should return `true` if the given object is a Zepto
  156. // collection. This method can be overridden in plugins.
  157. zepto.isZ = function(object) {
  158. return object instanceof zepto.Z
  159. }
  160. // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
  161. // takes a CSS selector and an optional context (and handles various
  162. // special cases).
  163. // This method can be overridden in plugins.
  164. zepto.init = function(selector, context) {
  165. var dom
  166. // If nothing given, return an empty Zepto collection
  167. if (!selector) return zepto.Z()
  168. // Optimize for string selectors
  169. else if (typeof selector == 'string') {
  170. selector = selector.trim()
  171. // If it's a html fragment, create nodes from it
  172. // Note: In both Chrome 21 and Firefox 15, DOM error 12
  173. // is thrown if the fragment doesn't begin with <
  174. if (selector[0] == '<' && fragmentRE.test(selector))
  175. dom = zepto.fragment(selector, RegExp.$1, context), selector = null
  176. // If there's a context, create a collection on that context first, and select
  177. // nodes from there
  178. else if (context !== undefined) return $(context).find(selector)
  179. // If it's a CSS selector, use it to select nodes.
  180. else dom = zepto.qsa(document, selector)
  181. }
  182. // If a function is given, call it when the DOM is ready
  183. else if (isFunction(selector)) return $(document).ready(selector)
  184. // If a Zepto collection is given, just return it
  185. else if (zepto.isZ(selector)) return selector
  186. else {
  187. // normalize array if an array of nodes is given
  188. if (isArray(selector)) dom = compact(selector)
  189. // Wrap DOM nodes.
  190. else if (isObject(selector))
  191. dom = [selector], selector = null
  192. // If it's a html fragment, create nodes from it
  193. else if (fragmentRE.test(selector))
  194. dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
  195. // If there's a context, create a collection on that context first, and select
  196. // nodes from there
  197. else if (context !== undefined) return $(context).find(selector)
  198. // And last but no least, if it's a CSS selector, use it to select nodes.
  199. else dom = zepto.qsa(document, selector)
  200. }
  201. // create a new Zepto collection from the nodes found
  202. return zepto.Z(dom, selector)
  203. }
  204. // `$` will be the base `Zepto` object. When calling this
  205. // function just call `$.zepto.init, which makes the implementation
  206. // details of selecting nodes and creating Zepto collections
  207. // patchable in plugins.
  208. $ = function(selector, context){
  209. return zepto.init(selector, context)
  210. }
  211. function extend(target, source, deep) {
  212. for (key in source)
  213. if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
  214. if (isPlainObject(source[key]) && !isPlainObject(target[key]))
  215. target[key] = {}
  216. if (isArray(source[key]) && !isArray(target[key]))
  217. target[key] = []
  218. extend(target[key], source[key], deep)
  219. }
  220. else if (source[key] !== undefined) target[key] = source[key]
  221. }
  222. // Copy all but undefined properties from one or more
  223. // objects to the `target` object.
  224. $.extend = function(target){
  225. var deep, args = slice.call(arguments, 1)
  226. if (typeof target == 'boolean') {
  227. deep = target
  228. target = args.shift()
  229. }
  230. args.forEach(function(arg){ extend(target, arg, deep) })
  231. return target
  232. }
  233. // `$.zepto.qsa` is Zepto's CSS selector implementation which
  234. // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
  235. // This method can be overridden in plugins.
  236. zepto.qsa = function(element, selector){
  237. var found,
  238. maybeID = selector[0] == '#',
  239. maybeClass = !maybeID && selector[0] == '.',
  240. nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
  241. isSimple = simpleSelectorRE.test(nameOnly)
  242. return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById
  243. ( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
  244. (element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] :
  245. slice.call(
  246. isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName
  247. maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
  248. element.getElementsByTagName(selector) : // Or a tag
  249. element.querySelectorAll(selector) // Or it's not simple, and we need to query all
  250. )
  251. }
  252. function filtered(nodes, selector) {
  253. return selector == null ? $(nodes) : $(nodes).filter(selector)
  254. }
  255. $.contains = document.documentElement.contains ?
  256. function(parent, node) {
  257. return parent !== node && parent.contains(node)
  258. } :
  259. function(parent, node) {
  260. while (node && (node = node.parentNode))
  261. if (node === parent) return true
  262. return false
  263. }
  264. function funcArg(context, arg, idx, payload) {
  265. return isFunction(arg) ? arg.call(context, idx, payload) : arg
  266. }
  267. function setAttribute(node, name, value) {
  268. value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
  269. }
  270. // access className property while respecting SVGAnimatedString
  271. function className(node, value){
  272. var klass = node.className || '',
  273. svg = klass && klass.baseVal !== undefined
  274. if (value === undefined) return svg ? klass.baseVal : klass
  275. svg ? (klass.baseVal = value) : (node.className = value)
  276. }
  277. // "true" => true
  278. // "false" => false
  279. // "null" => null
  280. // "42" => 42
  281. // "42.5" => 42.5
  282. // "08" => "08"
  283. // JSON => parse if valid
  284. // String => self
  285. function deserializeValue(value) {
  286. try {
  287. return value ?
  288. value == "true" ||
  289. ( value == "false" ? false :
  290. value == "null" ? null :
  291. +value + "" == value ? +value :
  292. /^[\[\{]/.test(value) ? $.parseJSON(value) :
  293. value )
  294. : value
  295. } catch(e) {
  296. return value
  297. }
  298. }
  299. $.type = type
  300. $.isFunction = isFunction
  301. $.isWindow = isWindow
  302. $.isArray = isArray
  303. $.isPlainObject = isPlainObject
  304. $.isEmptyObject = function(obj) {
  305. var name
  306. for (name in obj) return false
  307. return true
  308. }
  309. $.isNumeric = function(val) {
  310. var num = Number(val), type = typeof val
  311. return val != null && type != 'boolean' &&
  312. (type != 'string' || val.length) &&
  313. !isNaN(num) && isFinite(num) || false
  314. }
  315. $.inArray = function(elem, array, i){
  316. return emptyArray.indexOf.call(array, elem, i)
  317. }
  318. $.camelCase = camelize
  319. $.trim = function(str) {
  320. return str == null ? "" : String.prototype.trim.call(str)
  321. }
  322. // plugin compatibility
  323. $.uuid = 0
  324. $.support = { }
  325. $.expr = { }
  326. $.noop = function() {}
  327. $.map = function(elements, callback){
  328. var value, values = [], i, key
  329. if (likeArray(elements))
  330. for (i = 0; i < elements.length; i++) {
  331. value = callback(elements[i], i)
  332. if (value != null) values.push(value)
  333. }
  334. else
  335. for (key in elements) {
  336. value = callback(elements[key], key)
  337. if (value != null) values.push(value)
  338. }
  339. return flatten(values)
  340. }
  341. $.each = function(elements, callback){
  342. var i, key
  343. if (likeArray(elements)) {
  344. for (i = 0; i < elements.length; i++)
  345. if (callback.call(elements[i], i, elements[i]) === false) return elements
  346. } else {
  347. for (key in elements)
  348. if (callback.call(elements[key], key, elements[key]) === false) return elements
  349. }
  350. return elements
  351. }
  352. $.grep = function(elements, callback){
  353. return filter.call(elements, callback)
  354. }
  355. if (window.JSON) $.parseJSON = JSON.parse
  356. // Populate the class2type map
  357. $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
  358. class2type[ "[object " + name + "]" ] = name.toLowerCase()
  359. })
  360. // Define methods that will be available on all
  361. // Zepto collections
  362. $.fn = {
  363. constructor: zepto.Z,
  364. length: 0,
  365. // Because a collection acts like an array
  366. // copy over these useful array functions.
  367. forEach: emptyArray.forEach,
  368. reduce: emptyArray.reduce,
  369. push: emptyArray.push,
  370. sort: emptyArray.sort,
  371. splice: emptyArray.splice,
  372. indexOf: emptyArray.indexOf,
  373. concat: function(){
  374. var i, value, args = []
  375. for (i = 0; i < arguments.length; i++) {
  376. value = arguments[i]
  377. args[i] = zepto.isZ(value) ? value.toArray() : value
  378. }
  379. return concat.apply(zepto.isZ(this) ? this.toArray() : this, args)
  380. },
  381. // `map` and `slice` in the jQuery API work differently
  382. // from their array counterparts
  383. map: function(fn){
  384. return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
  385. },
  386. slice: function(){
  387. return $(slice.apply(this, arguments))
  388. },
  389. ready: function(callback){
  390. // need to check if document.body exists for IE as that browser reports
  391. // document ready when it hasn't yet created the body element
  392. if (readyRE.test(document.readyState) && document.body) callback($)
  393. else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
  394. return this
  395. },
  396. get: function(idx){
  397. return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
  398. },
  399. toArray: function(){ return this.get() },
  400. size: function(){
  401. return this.length
  402. },
  403. remove: function(){
  404. return this.each(function(){
  405. if (this.parentNode != null)
  406. this.parentNode.removeChild(this)
  407. })
  408. },
  409. each: function(callback){
  410. emptyArray.every.call(this, function(el, idx){
  411. return callback.call(el, idx, el) !== false
  412. })
  413. return this
  414. },
  415. filter: function(selector){
  416. if (isFunction(selector)) return this.not(this.not(selector))
  417. return $(filter.call(this, function(element){
  418. return zepto.matches(element, selector)
  419. }))
  420. },
  421. add: function(selector,context){
  422. return $(uniq(this.concat($(selector,context))))
  423. },
  424. is: function(selector){
  425. return this.length > 0 && zepto.matches(this[0], selector)
  426. },
  427. not: function(selector){
  428. var nodes=[]
  429. if (isFunction(selector) && selector.call !== undefined)
  430. this.each(function(idx){
  431. if (!selector.call(this,idx)) nodes.push(this)
  432. })
  433. else {
  434. var excludes = typeof selector == 'string' ? this.filter(selector) :
  435. (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
  436. this.forEach(function(el){
  437. if (excludes.indexOf(el) < 0) nodes.push(el)
  438. })
  439. }
  440. return $(nodes)
  441. },
  442. has: function(selector){
  443. return this.filter(function(){
  444. return isObject(selector) ?
  445. $.contains(this, selector) :
  446. $(this).find(selector).size()
  447. })
  448. },
  449. eq: function(idx){
  450. return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
  451. },
  452. first: function(){
  453. var el = this[0]
  454. return el && !isObject(el) ? el : $(el)
  455. },
  456. last: function(){
  457. var el = this[this.length - 1]
  458. return el && !isObject(el) ? el : $(el)
  459. },
  460. find: function(selector){
  461. var result, $this = this
  462. if (!selector) result = $()
  463. else if (typeof selector == 'object')
  464. result = $(selector).filter(function(){
  465. var node = this
  466. return emptyArray.some.call($this, function(parent){
  467. return $.contains(parent, node)
  468. })
  469. })
  470. else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
  471. else result = this.map(function(){ return zepto.qsa(this, selector) })
  472. return result
  473. },
  474. closest: function(selector, context){
  475. var nodes = [], collection = typeof selector == 'object' && $(selector)
  476. this.each(function(_, node){
  477. while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
  478. node = node !== context && !isDocument(node) && node.parentNode
  479. if (node && nodes.indexOf(node) < 0) nodes.push(node)
  480. })
  481. return $(nodes)
  482. },
  483. parents: function(selector){
  484. var ancestors = [], nodes = this
  485. while (nodes.length > 0)
  486. nodes = $.map(nodes, function(node){
  487. if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
  488. ancestors.push(node)
  489. return node
  490. }
  491. })
  492. return filtered(ancestors, selector)
  493. },
  494. parent: function(selector){
  495. return filtered(uniq(this.pluck('parentNode')), selector)
  496. },
  497. children: function(selector){
  498. return filtered(this.map(function(){ return children(this) }), selector)
  499. },
  500. contents: function() {
  501. return this.map(function() { return this.contentDocument || slice.call(this.childNodes) })
  502. },
  503. siblings: function(selector){
  504. return filtered(this.map(function(i, el){
  505. return filter.call(children(el.parentNode), function(child){ return child!==el })
  506. }), selector)
  507. },
  508. empty: function(){
  509. return this.each(function(){ this.innerHTML = '' })
  510. },
  511. // `pluck` is borrowed from Prototype.js
  512. pluck: function(property){
  513. return $.map(this, function(el){ return el[property] })
  514. },
  515. show: function(){
  516. return this.each(function(){
  517. this.style.display == "none" && (this.style.display = '')
  518. if (getComputedStyle(this, '').getPropertyValue("display") == "none")
  519. this.style.display = defaultDisplay(this.nodeName)
  520. })
  521. },
  522. replaceWith: function(newContent){
  523. return this.before(newContent).remove()
  524. },
  525. wrap: function(structure){
  526. var func = isFunction(structure)
  527. if (this[0] && !func)
  528. var dom = $(structure).get(0),
  529. clone = dom.parentNode || this.length > 1
  530. return this.each(function(index){
  531. $(this).wrapAll(
  532. func ? structure.call(this, index) :
  533. clone ? dom.cloneNode(true) : dom
  534. )
  535. })
  536. },
  537. wrapAll: function(structure){
  538. if (this[0]) {
  539. $(this[0]).before(structure = $(structure))
  540. var children
  541. // drill down to the inmost element
  542. while ((children = structure.children()).length) structure = children.first()
  543. $(structure).append(this)
  544. }
  545. return this
  546. },
  547. wrapInner: function(structure){
  548. var func = isFunction(structure)
  549. return this.each(function(index){
  550. var self = $(this), contents = self.contents(),
  551. dom = func ? structure.call(this, index) : structure
  552. contents.length ? contents.wrapAll(dom) : self.append(dom)
  553. })
  554. },
  555. unwrap: function(){
  556. this.parent().each(function(){
  557. $(this).replaceWith($(this).children())
  558. })
  559. return this
  560. },
  561. clone: function(){
  562. return this.map(function(){ return this.cloneNode(true) })
  563. },
  564. hide: function(){
  565. return this.css("display", "none")
  566. },
  567. toggle: function(setting){
  568. return this.each(function(){
  569. var el = $(this)
  570. ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
  571. })
  572. },
  573. prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
  574. next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
  575. html: function(html){
  576. return 0 in arguments ?
  577. this.each(function(idx){
  578. var originHtml = this.innerHTML
  579. $(this).empty().append( funcArg(this, html, idx, originHtml) )
  580. }) :
  581. (0 in this ? this[0].innerHTML : null)
  582. },
  583. text: function(text){
  584. return 0 in arguments ?
  585. this.each(function(idx){
  586. var newText = funcArg(this, text, idx, this.textContent)
  587. this.textContent = newText == null ? '' : ''+newText
  588. }) :
  589. (0 in this ? this.pluck('textContent').join("") : null)
  590. },
  591. attr: function(name, value){
  592. var result
  593. return (typeof name == 'string' && !(1 in arguments)) ?
  594. (0 in this && this[0].nodeType == 1 && (result = this[0].getAttribute(name)) != null ? result : undefined) :
  595. this.each(function(idx){
  596. if (this.nodeType !== 1) return
  597. if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
  598. else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
  599. })
  600. },
  601. removeAttr: function(name){
  602. return this.each(function(){ this.nodeType === 1 && name.split(' ').forEach(function(attribute){
  603. setAttribute(this, attribute)
  604. }, this)})
  605. },
  606. prop: function(name, value){
  607. name = propMap[name] || name
  608. return (1 in arguments) ?
  609. this.each(function(idx){
  610. this[name] = funcArg(this, value, idx, this[name])
  611. }) :
  612. (this[0] && this[0][name])
  613. },
  614. removeProp: function(name){
  615. name = propMap[name] || name
  616. return this.each(function(){ delete this[name] })
  617. },
  618. data: function(name, value){
  619. var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase()
  620. var data = (1 in arguments) ?
  621. this.attr(attrName, value) :
  622. this.attr(attrName)
  623. return data !== null ? deserializeValue(data) : undefined
  624. },
  625. val: function(value){
  626. if (0 in arguments) {
  627. if (value == null) value = ""
  628. return this.each(function(idx){
  629. this.value = funcArg(this, value, idx, this.value)
  630. })
  631. } else {
  632. return this[0] && (this[0].multiple ?
  633. $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
  634. this[0].value)
  635. }
  636. },
  637. offset: function(coordinates){
  638. if (coordinates) return this.each(function(index){
  639. var $this = $(this),
  640. coords = funcArg(this, coordinates, index, $this.offset()),
  641. parentOffset = $this.offsetParent().offset(),
  642. props = {
  643. top: coords.top - parentOffset.top,
  644. left: coords.left - parentOffset.left
  645. }
  646. if ($this.css('position') == 'static') props['position'] = 'relative'
  647. $this.css(props)
  648. })
  649. if (!this.length) return null
  650. if (document.documentElement !== this[0] && !$.contains(document.documentElement, this[0]))
  651. return {top: 0, left: 0}
  652. var obj = this[0].getBoundingClientRect()
  653. return {
  654. left: obj.left + window.pageXOffset,
  655. top: obj.top + window.pageYOffset,
  656. width: Math.round(obj.width),
  657. height: Math.round(obj.height)
  658. }
  659. },
  660. css: function(property, value){
  661. if (arguments.length < 2) {
  662. var element = this[0]
  663. if (typeof property == 'string') {
  664. if (!element) return
  665. return element.style[camelize(property)] || getComputedStyle(element, '').getPropertyValue(property)
  666. } else if (isArray(property)) {
  667. if (!element) return
  668. var props = {}
  669. var computedStyle = getComputedStyle(element, '')
  670. $.each(property, function(_, prop){
  671. props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
  672. })
  673. return props
  674. }
  675. }
  676. var css = ''
  677. if (type(property) == 'string') {
  678. if (!value && value !== 0)
  679. this.each(function(){ this.style.removeProperty(dasherize(property)) })
  680. else
  681. css = dasherize(property) + ":" + maybeAddPx(property, value)
  682. } else {
  683. for (key in property)
  684. if (!property[key] && property[key] !== 0)
  685. this.each(function(){ this.style.removeProperty(dasherize(key)) })
  686. else
  687. css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
  688. }
  689. return this.each(function(){ this.style.cssText += ';' + css })
  690. },
  691. index: function(element){
  692. return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
  693. },
  694. hasClass: function(name){
  695. if (!name) return false
  696. return emptyArray.some.call(this, function(el){
  697. return this.test(className(el))
  698. }, classRE(name))
  699. },
  700. addClass: function(name){
  701. if (!name) return this
  702. return this.each(function(idx){
  703. if (!('className' in this)) return
  704. classList = []
  705. var cls = className(this), newName = funcArg(this, name, idx, cls)
  706. newName.split(/\s+/g).forEach(function(klass){
  707. if (!$(this).hasClass(klass)) classList.push(klass)
  708. }, this)
  709. classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
  710. })
  711. },
  712. removeClass: function(name){
  713. return this.each(function(idx){
  714. if (!('className' in this)) return
  715. if (name === undefined) return className(this, '')
  716. classList = className(this)
  717. funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
  718. classList = classList.replace(classRE(klass), " ")
  719. })
  720. className(this, classList.trim())
  721. })
  722. },
  723. toggleClass: function(name, when){
  724. if (!name) return this
  725. return this.each(function(idx){
  726. var $this = $(this), names = funcArg(this, name, idx, className(this))
  727. names.split(/\s+/g).forEach(function(klass){
  728. (when === undefined ? !$this.hasClass(klass) : when) ?
  729. $this.addClass(klass) : $this.removeClass(klass)
  730. })
  731. })
  732. },
  733. scrollTop: function(value){
  734. if (!this.length) return
  735. var hasScrollTop = 'scrollTop' in this[0]
  736. if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
  737. return this.each(hasScrollTop ?
  738. function(){ this.scrollTop = value } :
  739. function(){ this.scrollTo(this.scrollX, value) })
  740. },
  741. scrollLeft: function(value){
  742. if (!this.length) return
  743. var hasScrollLeft = 'scrollLeft' in this[0]
  744. if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset
  745. return this.each(hasScrollLeft ?
  746. function(){ this.scrollLeft = value } :
  747. function(){ this.scrollTo(value, this.scrollY) })
  748. },
  749. position: function() {
  750. if (!this.length) return
  751. var elem = this[0],
  752. // Get *real* offsetParent
  753. offsetParent = this.offsetParent(),
  754. // Get correct offsets
  755. offset = this.offset(),
  756. parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset()
  757. // Subtract element margins
  758. // note: when an element has margin: auto the offsetLeft and marginLeft
  759. // are the same in Safari causing offset.left to incorrectly be 0
  760. offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
  761. offset.left -= parseFloat( $(elem).css('margin-left') ) || 0
  762. // Add offsetParent borders
  763. parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0
  764. parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0
  765. // Subtract the two offsets
  766. return {
  767. top: offset.top - parentOffset.top,
  768. left: offset.left - parentOffset.left
  769. }
  770. },
  771. offsetParent: function() {
  772. return this.map(function(){
  773. var parent = this.offsetParent || document.body
  774. while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
  775. parent = parent.offsetParent
  776. return parent
  777. })
  778. }
  779. }
  780. // for now
  781. $.fn.detach = $.fn.remove
  782. // Generate the `width` and `height` functions
  783. ;['width', 'height'].forEach(function(dimension){
  784. var dimensionProperty =
  785. dimension.replace(/./, function(m){ return m[0].toUpperCase() })
  786. $.fn[dimension] = function(value){
  787. var offset, el = this[0]
  788. if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
  789. isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
  790. (offset = this.offset()) && offset[dimension]
  791. else return this.each(function(idx){
  792. el = $(this)
  793. el.css(dimension, funcArg(this, value, idx, el[dimension]()))
  794. })
  795. }
  796. })
  797. function traverseNode(node, fun) {
  798. fun(node)
  799. for (var i = 0, len = node.childNodes.length; i < len; i++)
  800. traverseNode(node.childNodes[i], fun)
  801. }
  802. // Generate the `after`, `prepend`, `before`, `append`,
  803. // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
  804. adjacencyOperators.forEach(function(operator, operatorIndex) {
  805. var inside = operatorIndex % 2 //=> prepend, append
  806. $.fn[operator] = function(){
  807. // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
  808. var argType, nodes = $.map(arguments, function(arg) {
  809. var arr = []
  810. argType = type(arg)
  811. if (argType == "array") {
  812. arg.forEach(function(el) {
  813. if (el.nodeType !== undefined) return arr.push(el)
  814. else if ($.zepto.isZ(el)) return arr = arr.concat(el.get())
  815. arr = arr.concat(zepto.fragment(el))
  816. })
  817. return arr
  818. }
  819. return argType == "object" || arg == null ?
  820. arg : zepto.fragment(arg)
  821. }),
  822. parent, copyByClone = this.length > 1
  823. if (nodes.length < 1) return this
  824. return this.each(function(_, target){
  825. parent = inside ? target : target.parentNode
  826. // convert all methods to a "before" operation
  827. target = operatorIndex == 0 ? target.nextSibling :
  828. operatorIndex == 1 ? target.firstChild :
  829. operatorIndex == 2 ? target :
  830. null
  831. var parentInDocument = $.contains(document.documentElement, parent)
  832. nodes.forEach(function(node){
  833. if (copyByClone) node = node.cloneNode(true)
  834. else if (!parent) return $(node).remove()
  835. parent.insertBefore(node, target)
  836. if (parentInDocument) traverseNode(node, function(el){
  837. if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
  838. (!el.type || el.type === 'text/javascript') && !el.src){
  839. var target = el.ownerDocument ? el.ownerDocument.defaultView : window
  840. target['eval'].call(target, el.innerHTML)
  841. }
  842. })
  843. })
  844. })
  845. }
  846. // after => insertAfter
  847. // prepend => prependTo
  848. // before => insertBefore
  849. // append => appendTo
  850. $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
  851. $(html)[operator](this)
  852. return this
  853. }
  854. })
  855. zepto.Z.prototype = Z.prototype = $.fn
  856. // Export internal API functions in the `$.zepto` namespace
  857. zepto.uniq = uniq
  858. zepto.deserializeValue = deserializeValue
  859. $.zepto = zepto
  860. return $
  861. })()
  862. // If `$` is not yet defined, point it to `Zepto`
  863. window.Zepto = Zepto
  864. window.$ === undefined && (window.$ = Zepto)