Zepto.js

Zepto 是一个轻量级的、针对现代高级浏览器的 JavaScript 工具库,它兼容 jQuery 的 API如果你会用 jQuery,那么你就已经会用 Zepto 了。

Zepto 的设计目的是提供与 jQuery 兼容的 API,但并不是 100% 覆盖 jQuery API 。 Zepto 设计的目的是提供一个 5-10k 的通用库、下载并快速执行有一套大家熟悉且稳定的 API, 所以你能把你可以把主要的精力放到应用开发上

Zepto 是一款开源软件,它采用的是对开发者和商业都很友好的开源协议 -- MIT license

下载 Zepto

其他下载方式:

默认构建包含以下模块: Core, Ajax, Event, Form, IE.

如果 $ 变量尚未定义,Zepto 只设置全局变量 $ 指向它本身。 没有 Zepto.noConflict方法。

浏览器支持:

主要浏览器 (100% 支持)

次要浏览器 (全部或部分支持)

需要注意的是 Zepto 的一些可选功能是专门针对移动端浏览器的; 因为它的最初目标在移动端提供一个精简的类似 jQuery 的工具库。

在浏览器上(Safari、Chrome 和 Firefox)上开发页面应用或者构建基于 HTML 的 web-view 本地应用, 例如 PhoneGap,使用 Zepto 是一个不错的选择。

总之,Zepto 希望在所有的现代浏览器中作为一种基础环境来使用。 Zepto 不支持旧版本的 Internet Explorer浏览器(<10)。

手动构建 Zepto

上面提供的 zepto.jszepto.min.js 可以直接使用。 然而,为了更好的程序效果和自由性,可以通过 Zepto 源码构建 Zepto.js 和 zepto.min.js 的时候选择模块并作测试, 使用 UglifyJS 根据你的需要来生 成 zepto.min.js (当服务端开启gzipped后,最精简的代码)文件。

请参考 the README 文件了解如何构建 Zepto, 还有如何测试以及提交补丁的说明。

Zepto 模块

模块名 默认内置 描述
zepto Core module; contains most methods
event Event handling via on() & off()
ajax XMLHttpRequest and JSONP functionality
form Serialize & submit web forms
ie Add support for Internet Explorer 10+ on desktop and Windows Phone 8.
detect Provides $.os and $.browser information
fx The animate() method
fx_methods Animated show, hide, toggle, and fade*() methods.
assets Experimental support for cleaning up iOS memory after removing image elements from the DOM.
data A full-blown data() method, capable of storing arbitrary objects in memory.
deferred Provides $.Deferred promises API. Depends on the "callbacks" module.
When included, $.ajax() supports a promise interface for chaining callbacks.
callbacks Provides $.Callbacks for use in "deferred" module.
selector Experimental jQuery CSS extensions support for functionality such as $('div:first') and el.is(':visible').
touch Fires tap– and swipe–related events on touch devices. This works with both `touch` (iOS, Android) and `pointer` events (Windows Phone).
gesture Fires pinch gesture events on touch devices
stack Provides andSelf & end() chaining methods
ios3 String.prototype.trim and Array.prototype.reduce methods (if they are missing) for compatibility with iOS 3.x.

创建插件

Plugins can be written by adding methods as properties of $.fn:

;(function($){
  $.extend($.fn, {
    foo: function(){
      // `this` refers to the current Zepto collection.
      // When possible, return the Zepto collection to allow chaining.
      return this.html('bar')
    }
  })
})(Zepto)

To get started with plug-in development, take a look at the source of Zepto's core module, and be sure to read the coding style guidelines.


核心方法

$()

$(selector, [context]) ⇒ collection
$(<Zepto collection>) ⇒ same collection
$(<DOM nodes>) ⇒ collection
$(htmlString) ⇒ collection
$(htmlString, attributes) ⇒ collection [v1.0]
Zepto(function($){ ... })

Create a Zepto collection object by performing a CSS selector, wrapping DOM nodes, or creating elements from an HTML string.

A Zepto collection is an array-like object that has chainable methods for manipulating the DOM nodes it references. All of the methods in this documentation are collection methods, except the ones directly on the dollar (Zepto) object, such as $.extend.

If a context (CSS selector, DOM node or Zepto collection object) is given, perform the CSS selector only within nodes of the context; this is functionally the same as calling $(context).find(selector).

When an HTML string is given, use it to create DOM nodes. If an attributes map is given via argument, apply them to all created elements. For fast single element creation, use <div> or <div/> forms.

When a function is given, attach it as a handler for the DOMContentLoaded event. If the page is already loaded, executes the function immediately.

$('div')  //=> all DIV elements on the page
$('#foo') //=> element with ID "foo"

// create element:
$("<p>Hello</p>") //=> the new P element
// create element with attributes:
$("<p />", { text:"Hello", id:"greeting", css:{color:'darkblue'} })
//=> <p id=greeting style="color:darkblue">Hello</p>

// execute callback when the page is ready:
Zepto(function($){
  alert('Ready to Zepto!')
})

jQuery CSS extensions are not supported. However, the optional “selector” module provides limited support for a few of the most used pseudo-selectors, and can be dropped in for compatibility with existing code or plugins.

Zepto will only set the $ global to itself if it is not yet defined. This allows you to use Zepto with legacy code that uses, for example, Prototype.js. Just load Prototype first, and Zepto will not touch Prototype’s $ function. Zepto will always set the Zepto global to itself.

$.camelCase v1.0+

$.camelCase(string) ⇒ string

Turn a dasherized string into “camel case”. Doesn’t affect already camel-cased strings.

$.camelCase('hello-there') //=> "helloThere"
$.camelCase('helloThere')  //=> "helloThere"

$.contains v1.0+

$.contains(parent, node) ⇒ boolean

Check if the parent node contains the given DOM node. Returns false if both are the same node.

$.each

$.each(collection, function(index, item){ ... }) ⇒ collection

Iterate over array elements or object key-value pairs. Returning false from the iterator function stops the iteration.

$.each(['a', 'b', 'c'], function(index, item){
  console.log('item %d is: %s', index, item)
})

var hash = { name: 'zepto.js', size: 'micro' }
$.each(hash, function(key, value){
  console.log('%s: %s', key, value)
})

$.extend

$.extend(target, [source, [source2, ...]]) ⇒ target
$.extend(true, target, [source, ...]) ⇒ target [v1.0]

Extend target object with properties from each of the source objects, overriding the properties on target.

By default, copying is shallow. An optional true for the first argument triggers deep (recursive) copying.

var target = { one: 'patridge' },
    source = { two: 'turtle doves' }

$.extend(target, source)
//=> { one: 'patridge',
//     two: 'turtle doves' }

$.fn

Zepto.fn is an object that holds all of the methods that are available on Zepto collections, such as addClass(), attr(), and other. Adding a function to this object makes that method available on every Zepto collection.

Here’s an example implementation of Zepto’s empty() method:

$.fn.empty = function(){
  return this.each(function(){ this.innerHTML = '' })
}

$.grep v1.0+

$.grep(items, function(item){ ... }) ⇒ array

Get a new array containing only the items for which the callback function returned true.

$.inArray v1.0+

$.inArray(element, array, [fromIndex]) ⇒ number

Get the position of element inside an array, or -1 if not found.

$.isArray

$.isArray(object) ⇒ boolean

True if the object is an array.

$.isFunction

$.isFunction(object) ⇒ boolean

True if the object is a function.

$.isNumeric v1.2+

$.isNumeric(value) ⇒ boolean

True if the value is a finite Number or a String representing a number.

$.isPlainObject v1.0+

$.isPlainObject(object) ⇒ boolean

True if the object is a “plain” JavaScript object, which is only true for object literals and objects created with new Object.

$.isPlainObject({})         // => true
$.isPlainObject(new Object) // => true
$.isPlainObject(new Date)   // => false
$.isPlainObject(window)     // => false

$.isWindow v1.0+

$.isWindow(object) ⇒ boolean

True if the object is a window object. This is useful for iframes where each one has its own window, and where these objects fail the regular obj === window check.

$.map

$.map(collection, function(item, index){ ... }) ⇒ collection

Iterate through elements of collection and return all results of running the iterator function, with null and undefined values filtered out.

$.noop v1.2+

var callback = $.noop

A reference to a function that does nothing.

$.parseJSON v1.0+

$.parseJSON(string) ⇒ object

Alias for the native JSON.parse method.

$.trim v1.0+

$.trim(string) ⇒ string

Remove whitespace from beginning and end of a string; just like String.prototype.trim().

$.type v1.0+

$.type(object) ⇒ string

Get string type of an object. Possible types are: null undefined boolean number string function array date regexp object error.

For other objects it will simply report “object”. To find out if an object is a plain JavaScript object, use isPlainObject.

add

add(selector, [context]) ⇒ self

添加元素到当前匹配的元素集合中。如果给定 context 参数,将只在 context 元素中根据 CSS 选择器(selector)进行查找,否则在整个 document 中查找。

addClass

addClass(name) ⇒ self
addClass(function(index, oldClassName){ ... }) ⇒ self

为每个匹配的元素添加指定的c lass 类名。多个 class 类名使用空格分隔。

after

after(content) ⇒ self

在每个匹配的元素后面插入内容。内容可以为 HTML 字符串、DOM 节点或者由节点组成的数组。

$('form label').after('<p>A note below the label</p>')

append

append(content) ⇒ self

在每个匹配的元素的内部的末尾插入内容。内容可以为 HTML 字符串、DOM节点或者节点组成的数组。

$('ul').append('<li>new list item</li>')

appendTo

appendTo(target) ⇒ self

将匹配的元素插入到目标元素的内部的末尾。这个有点像 append,但是插入的目标与其相反。

$('<li>new list item</li>').appendTo('ul')

attr

attr(name) ⇒ string
attr(name, value) ⇒ self
attr(name, function(index, oldValue){ ... }) ⇒ self
attr({ name: value, name2: value2, ... }) ⇒ self

读取或设置 DOM 的属性。如果没有给定 value 参数,则读取对象集合中第一个元素的属性值。当给定了 value 参数。则设置对象集合中所有元素的该属性的值。当 value 参数为 null,那么这个属性将被移除(类似 removeAttr),多个属性可以通过对象键值对的方式进行设置。

要读取 DOM 的属性如 checkedselected, 使用 prop 方法。

var form = $('form')
form.attr('action')             //=> 读取值
form.attr('action', '/create')  //=> 设置值
form.attr('action', null)       //=> 删除属性

// 同时操作多个属性:
form.attr({
  action: '/create',
  method: 'post'
})

before

before(content) ⇒ self

在每个匹配元素的前面插入内容。内容可以为 HTML 字符串、DOM 节点或者节点组成的数组。

$('table').before('<p>See the following table:</p>')

children

children([selector]) ⇒ collection

获得元素集合中的每个元素的直接子元素,如果给定 selector,那么返回的结果中只包含符合 CSS 选择器(selector)的元素。

$('ol').children('*:nth-child(2n)')
//=> every other list item from every ordered list

clone v1.0+

clone() ⇒ collection

通过深度克隆来复制集合中的所有元素。

This method doesn't have an option for copying data and event handlers over to the new elements, as it has in jQuery.

closest

closest(selector, [context]) ⇒ collection
closest(collection) ⇒ collection [v1.0]
closest(element) ⇒ collection [v1.0]

从元素本身开始,逐级向上级元素匹配,并返回最先匹配 selector 的元素。如果给定 context 节点参数,那么只匹配该节点的后代元素。这个方法与 parents(selector) 有点相像,但它只返回最先匹配的祖先元素。

如果参数是一个 Zepto 对象集合或者一个元素,结果必须匹配给定的元素而不是选择器(selector)。

var input = $('input[type=text]')
input.closest('form')

concat

concat(nodes, [node2, ...]) ⇒ self

添加元素到一个元素集合中。如果参数是一个数组,那么这个数组中的所有元素将会合并到当前元素集合中。

This is a Zepto-provided method that is not part of the jQuery API.

contents v1.0+

contents() ⇒ collection

获取元素集合中的每个元素的子元素,包括文字和注释节点。

css

css(property) ⇒ value
css([property1, property2, ...]) ⇒ object [v1.1]
css(property, value) ⇒ self
css({ property: value, property2: value2, ... }) ⇒ self

读取或设置 DOM 元素的 CSS 属性。当 value 参数不存在的时候,返回对象集合中第一个元素的 CSS 属性。当 value 参数存在时,设置对象集合中每一个元素的对应 CSS 属性。

多个属性可以通过传递一个属性名组成的数组一次性获取。多个属性可以利用对象键值对的方式进行设置。

当 value 为空(空字符串,null 或 undefined),那个 CSS 属性将会被移出。当 value 参数为一个无单位的数字,如果该 CSS 属性需要单位,“px” 将会自动添加到该属性上。

var elem = $('h1')
elem.css('background-color')          // 读取属性值
elem.css('background-color', '#369')  // 设置属性值
elem.css('background-color', '')      // 移除属性

// set multiple properties:
elem.css({ backgroundColor: '#8EE', fontSize: 28 })

// read multiple properties:
elem.css(['backgroundColor', 'fontSize'])['fontSize']

data

data(name) ⇒ value
data(name, value) ⇒ self

Read or write data-* DOM attributes. Behaves like attr, but prepends data- to the attribute name.

When reading attribute values, the following conversions apply: v1.0+

  • “true”, “false”, and “null” are converted to corresponding types;
  • number values are converted to actual numeric types;
  • JSON values are parsed, if it’s valid JSON;
  • everything else is returned as string.

Zepto's basic implementation of `data()` only stores strings. To store arbitrary objects, include the optional "data" module in your custom build of Zepto.

each

each(function(index, item){ ... }) ⇒ self

遍历一个对象集合每个元素。在迭代函数中,this 关键字指向当前项(作为函数的第二个参数传递)。如果迭代函数返回 false,遍历结束。

$('form input').each(function(index){
  console.log('input %d is: %o', index, this)
})

empty

empty() ⇒ self

清空对象集合中每个元素的 DOM 内容。

eq

eq(index) ⇒ collection

从当前对象集合中获取给定索引值的元素。

$('li').eq(0)   //=> 只选取第一个元素
$('li').eq(-1)  //=> 只选取最后一个元素

filter

filter(selector) ⇒ collection
filter(function(index){ ... }) ⇒ collection [v1.0]

过滤对象集合,返回对象集合中满足 CSS 选择器的项。如果参数为一个函数,函数返回有实际值得时候,元素才会被返回。在函数中, this 关键字指向当前的元素。

与此相反的功能,查看 not

find

find(selector) ⇒ collection
find(collection) ⇒ collection [v1.0]
find(element) ⇒ collection [v1.0]

在当对象前集合内查找符合 CSS 选择器的每个元素的后代元素。

如果给定 Zepto 对象集合或者元素,过滤它们,只有当它们在当前 Zepto 集合对象中时,才回被返回。

var form = $('#myform')
form.find('input, select')

first

first() ⇒ collection

获取当前对象集合中的第一个元素。

$('form').first()

forEach

forEach(function(item, index, array){ ... }, [context])

遍历对象集合中每个元素,有点类似 each,但是遍历函数的参数不一样,当函数返回 false 的时候,遍历不会停止。

这是一个 Zepto 提供的方法,在 jQuery 的 API 中没有对应的方法。

get

get() ⇒ array
get(index) ⇒ DOM node

从当前对象集合中获取所有元素或单个元素。当 index 参数不存在的时,以普通数组的方式返回所有的元素。当指定 index 时,只返回该置的元素。这点与 eq 不同,该方法返回的是 DOM 节点,不是 Zepto 对象集合。

var elements = $('h2')
elements.get()   //=> 获取所有标题组成的数组
elements.get(0)  //=> 获取第一个标题节点

has v1.0+

has(selector) ⇒ collection
has(node) ⇒ collection

判断当前对象集合的子元素是否有符合选择器的元素,或者是否包含指定的 DOM 节点,如果有,则返回新的对象集合,该对象过滤掉不含有选择器匹配元素或者不含有指定 DOM 节点的对象。

$('ol > li').has('a[href]')
//=> 只获取包含链接的 LI 元素。

hasClass

hasClass(name) ⇒ boolean

检查对象集合中是否有元素含有指定的 class 。

height

height() ⇒ number
height(value) ⇒ self
height(function(index, oldHeight){ ... }) ⇒ self

获取对象集合中第一个元素的高度;或者设置对象集合中所有元素的高度。

$('#foo').height()   // => 123
$(window).height()   // => 838 (viewport height)
$(document).height() // => 22302

hide

hide() ⇒ self

通过设置 CSS 的属性 displaynone 来将对象集合中的元素隐藏。

html

html() ⇒ string
html(content) ⇒ self
html(function(index, oldHtml){ ... }) ⇒ self

获取或设置对象集合中元素的 HTML 内容。当没有给定 content 参数时,返回对象集合中第一个元素的 innerHtml。当给定 content 参数时,用其替换对象集合中每个元素的内容。content 可以是 append 中描述的所有类型。

// autolink everything that looks like a Twitter username
$('.comment p').html(function(idx, oldHtml){
  return oldHtml.replace(/(^|\W)@(\w{1,15})/g,
    '$1@<a href="http://twitter.com/$2">$2</a>')
})

index

index([element]) ⇒ number

获取一个元素的索引值(从 0 开始计数)。当 elemen 参数没有给出时,返回当前元素在兄弟节点中的位置。当 element 参数给出时,返回它在当前对象集合中的位置。如果没有找到该元素,则返回 -1

$('li:nth-child(2)').index()  //=> 1

indexOf

indexOf(element, [fromIndex]) ⇒ number

在当前对象集合中获取一个元素的索引值(从0开始计数)。如果给定 fromIndex 参数,从该位置开始往后查找,返回以 0 开始计数的索引值,如果没找到,则返回 -1。推荐优先使用 index 方法。

这是一个 Zepto 提供的方法,在 jQuery 的 API 中没有对应的方法。

insertAfter

insertAfter(target) ⇒ self

将集合中的元素插入到指定的目标元素后面。这个有点像 after,但是参数顺序相反。

$('<p>Emphasis mine.</p>').insertAfter('blockquote')

insertBefore

insertBefore(target) ⇒ self

将集合中的元素插入到指定的目标元素前面。这个有点像 before,但是参数顺序相反。

$('<p>See the following table:</p>').insertBefore('table')

is

is(selector) ⇒ boolean

判断当前元素集合中的第一个元素是否符 CSS 选择器(selector)。为了支持基本的 jQuery 非标准选择器,例如: :visible ,务必引入可选的 “selector” 模块。

不支持 jQuery CSS extensions。可选的 “selector” 模块仅支持有限的几个常用方法。

last

last() ⇒ collection

获取对象集合中最后一个元素。

$('li').last()

map

map(function(index, item){ ... }) ⇒ collection

遍历对象集合中的所有元素。通过遍历函数返回值形成一个新的集合对象。在遍历函数中 this 关键之指向当前循环的项(遍历函数中的第二个参数)。

遍历函数的返回值组成一个新的集合并被返回,集合中的 nullundefined 全部被过滤掉,不会出现在集合中。

// get text contents of all elements in collection
elements.map(function(){ return $(this).text() }).get().join(', ')

next

next() ⇒ collection
next(selector) ⇒ collection [v1.0]

获取对象集合中每一个元素的下一个兄弟节点(可以选择性的带上过滤选择器)。

$('dl dt').next()   //=> the DD elements

not

not(selector) ⇒ collection
not(collection) ⇒ collection
not(function(index){ ... }) ⇒ collection

Filter the current collection to get a new collection of elements that don’t match the CSS selector. If another collection is given instead of selector, return only elements not present in it. If a function is given, return only elements for which the function returns a falsy value. Inside the function, the this keyword refers to the current element.

For the opposite, see filter.

offset

offset() ⇒ object
offset(coordinates) ⇒ self [v1.0]
offset(function(index, oldOffset){ ... }) ⇒ self [v1.0]

Get position of the element in the document. Returns an object with properties: top, left, width and height.

When given an object with properties left and top, use those values to position each element in the collection relative to the document.

offsetParent v1.0+

offsetParent() ⇒ collection

Find the first ancestor element that is positioned, meaning its CSS position value is “relative”, “absolute” or “fixed”.

parent

parent([selector]) ⇒ collection

Get immediate parents of each element in the collection. If CSS selector is given, filter results to include only ones matching the selector.

parents

parents([selector]) ⇒ collection

Get all ancestors of each element in the collection. If CSS selector is given, filter results to include only ones matching the selector.

To get only immediate parents, use parent. To only get the first ancestor that matches the selector, use closest.

$('h1').parents()   //=> [<div#container>, <body>, <html>]

pluck

pluck(property) ⇒ array

Get values from a named property of each element in the collection, with null and undefined values filtered out.

$('body > *').pluck('nodeName') // => ["DIV", "SCRIPT"]

// implementation of Zepto's `next` method
$.fn.next = function(){ 
  return $(this.pluck('nextElementSibling')) 
}

This is a Zepto-provided method that is not part of the jQuery API.

position v1.0+

position() ⇒ object

Get the position of the first element in the collection, relative to the offsetParent. This information is useful when absolutely positioning an element to appear aligned with another.

Returns an object with properties: top, left.

var pos = element.position()

// position a tooltip relative to the element
$('#tooltip').css({
  position: 'absolute',
  top: pos.top - 30,
  left: pos.left
})

prepend

prepend(content) ⇒ self

Prepend content to the DOM inside each element in the collection. The content can be an HTML string, a DOM node or an array of nodes.

$('ul').prepend('<li>first list item</li>')

prependTo

prependTo(target) ⇒ self

Prepend elements of the current collection inside each of the target elements. This is like prepend, only with reversed operands.

$('<li>first list item</li>').prependTo('ul')

prev

prev() ⇒ collection
prev(selector) ⇒ collection [v1.0]

Get the previous sibling–optionally filtered by selector–of each element in the collection.

prop v1.0+

prop(name) ⇒ value
prop(name, value) ⇒ self
prop(name, function(index, oldValue){ ... }) ⇒ self
prop({ name: value, name2: value2, ... }) ⇒ self

Read or set properties of DOM elements. This should be preferred over attr in case of reading values of properties that change with user interaction over time, such as checked and selected.

Short and lowercase names such as for, class, readonly and similar will be mapped to actual properties such as htmlFor, className, readOnly, etc.

push

push(element, [element2, ...]) ⇒ self

Add elements to the end of the current collection.

This is a Zepto-provided method that is not part of the jQuery API.

ready

ready(function($){ ... }) ⇒ self

Attach an event handler for the “DOMContentLoaded” event that fires when the DOM on the page is ready. It’s recommended to use the $() function instead of this method.

reduce

reduce(function(memo, item, index, array){ ... }, [initial]) ⇒ value

Identical to Array.reduce that iterates over current collection.

This is a Zepto-provided method that is not part of the jQuery API.

remove

remove() ⇒ self

Remove elements in the current collection from their parent nodes, effectively detaching them from the DOM.

removeAttr

removeAttr(name) ⇒ self

Remove the specified attribute from all elements in the collection. Multiple attributes to remove can be passed as a space-separated list.

removeClass

removeClass([name]) ⇒ self
removeClass(function(index, oldClassName){ ... }) ⇒ self

Remove the specified class name from all elements in the collection. When the class name isn’t given, remove all class names. Multiple class names can be given in a space-separated string.

removeProp v1.2+

removeProp(name) ⇒ self

Remove a property from each of the DOM nodes in the collection. This is done with JavaScript’s delete operator. Note that trying to remove some built-in DOM properties such as className or maxLength won’t have any affect, since browsers disallow removing those properties.

replaceWith

replaceWith(content) ⇒ self

Replace each element in the collection–both its contents and the element itself–with the new content. Content can be of any type described in before.

scrollLeft v1.1+

scrollLeft() ⇒ number
scrollLeft(value) ⇒ self

Gets or sets how many pixels were scrolled to the right so far on window or scrollable element on the page.

scrollTop v1.0+

scrollTop() ⇒ number
scrollTop(value) ⇒ self [v1.1]

Gets or sets how many pixels were scrolled down so far on window or scrollable element on the page.

show

show() ⇒ self

Restore the default value for the “display” property of each element in the array, effectively showing them if they were hidden with hide.

siblings

siblings([selector]) ⇒ collection

Get all sibling nodes of each element in the collection. If CSS selector is specified, filter the results to contain only elements that match the selector.

size

size() ⇒ number

Get the number of elements in this collection.

slice

slice(start, [end]) ⇒ array

Extract the subset of this array, starting at start index. If end is specified, extract up to but not including end index.

text

text() ⇒ string
text(content) ⇒ self
text(function(index, oldText){ ... }) ⇒ self [v1.1.4]

Get or set the text content of elements in the collection. When no content is given, returns the text contents of all the elements in the collection, if no element exists, null will be returned. When content is given, uses it to replace the text contents of each element in the collection. This is similar to html, with the exception it can’t be used for getting or setting HTML.

toggle

toggle([setting]) ⇒ self

Toggle between showing and hiding each of the elements, based on whether the first element is visible or not. If setting is present, this method behaves like show if setting is truthy or hide otherwise.

var input = $('input[type=text]')
$('#too_long').toggle(input.val().length > 140)

toggleClass

toggleClass(names, [setting]) ⇒ self
toggleClass(function(index, oldClassNames){ ... }, [setting]) ⇒ self

Toggle given class names (space-separated) in each element in the collection. The class name is removed if present on an element; otherwise it’s added. If setting is present, this method behaves like addClass if setting is truthy or removeClass otherwise.

unwrap

unwrap() ⇒ self

Remove immediate parent nodes of each element in the collection and put their children in their place. Basically, this method removes one level of ancestry while keeping current elements in the DOM.

$(document.body).append('<div id=wrapper><p>Content</p></div>')
$('#wrapper p').unwrap().parents()  //=> [<body>, <html>]

val

val() ⇒ string
val(value) ⇒ self
val(function(index, oldValue){ ... }) ⇒ self

Get or set the value of form controls. When no value is given, return the value of the first element. For <select multiple>, an array of values is returend. When a value is given, set all elements to this value.

width

width() ⇒ number
width(value) ⇒ self
width(function(index, oldWidth){ ... }) ⇒ self

Get the width of the first element in the collection; or set the width of all elements in the collection.

$('#foo').width()   // => 123
$(window).width()   // => 768 (viewport width)
$(document).width() // => 768 

wrap

wrap(structure) ⇒ self
wrap(function(index){ ... }) ⇒ self [v1.0]

Wrap each element of the collection separately in a DOM structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node, or as a function that is called for each element and returns one of the first two types.

Keep in mind that wrapping works best when operating on nodes that are part of the DOM. When calling wrap() on a new element and then inserting the result in the document, the element will lose the wrapping.

// wrap each button in a separate span:
$('.buttons a').wrap('<span>')

// wrap each code block in a div and pre:
$('code').wrap('<div class=highlight><pre /></div>')

// wrap all form inputs in a span with classname
// corresponding to input type:
$('input').wrap(function(index){
  return '<span class=' + this.type + 'field />'
})
//=> <span class=textfield><input type=text /></span>,
//   <span class=searchfield><input type=search /></span>

// WARNING: will not work as expected!
$('<em>broken</em>').wrap('<li>').appendTo(document.body)
// do this instead:
$('<em>better</em>').appendTo(document.body).wrap('<li>')

wrapAll

wrapAll(structure) ⇒ self

Wrap all elements in a single structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node.

// wrap all buttons in a single div:
$('a.button').wrapAll('<div id=buttons />')

wrapInner

wrapInner(structure) ⇒ self
wrapInner(function(index){ ... }) ⇒ self [v1.0]

Wrap the contents of each element separately in a structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node, or as a function that is called for each element and returns one of the first two types.

// wrap the contents of each navigation link in a span:
$('nav a').wrapInner('<span>')

// wrap the contents of each list item in a paragraph and emphasis:
$('ol li').wrapInner('<p><em /></p>')

Detect methods

Detect 模块

“detect” 模块对于站点或 app 针对不同环境调优很有用处,并且能帮助你识别手机和平板;以及不同的浏览器和操作系统。

// The following boolean flags are set to true if they apply,
// if not they're either set to `false` or `undefined`.
// We recommend accessing them with `!!` prefixed to coerce to a boolean.

// general device type
$.os.phone
$.os.tablet

// specific OS
$.os.ios
$.os.android
$.os.webos
$.os.blackberry
$.os.bb10
$.os.rimtabletos

// specific device type
$.os.iphone
$.os.ipad
$.os.ipod // [v1.1]
$.os.touchpad
$.os.kindle

// specific browser
$.browser.chrome
$.browser.firefox
$.browser.safari // [v1.1]
$.browser.webview // (iOS) [v1.1]
$.browser.silk
$.browser.playbook
$.browser.ie // [v1.1]

// Additionally, version information is available as well.
// Here's what's returned for an iPhone running iOS 6.1.
!!$.os.phone         // => true
!!$.os.iphone        // => true
!!$.os.ios           // => true
$.os.version       // => "6.1"
$.browser.version  // => "536.26"

事件处理

$.Event

$.Event(type, [properties]) ⇒ event

Create and initialize a DOM event of the specified type. If a properties object is given, use it to extend the new event object. The event is configured to bubble by default; this can be turned off by setting the bubbles property to false.

An event initialized with this function can be triggered with trigger.

$.Event('mylib:change', { bubbles: false })

$.proxy v1.0+

$.proxy(fn, context) ⇒ function
$.proxy(fn, context, [additionalArguments...]) ⇒ function [v1.1.4]
$.proxy(context, property) ⇒ function
$.proxy(context, property, [additionalArguments...]) ⇒ function [v1.1.4]

Get a function that ensures that the value of this in the original function refers to the context object. In the second form, the original function is read from the specific property of the context object.

If additional arguments are passed beyond the 2nd argument, they are applied to every invocation of the wrapped function in front of its actual arguments.

var obj = {name: 'Zepto'},
    handler = function(){ console.log("hello from + ", this.name) }

// ensures that the handler will be executed in the context of `obj`:
$(document).on('click', $.proxy(handler, obj))

bind 🦄🔨

Deprecated, use on instead.

bind(type, function(e){ ... }) ⇒ self
bind(type, [data], function(e){ ... }) ⇒ self [v1.1]
bind({ type: handler, type2: handler2, ... }) ⇒ self
bind({ type: handler, type2: handler2, ... }, [data]) ⇒ self [v1.1]

Attach an event handler to elements.

delegate 🦄🔨

Deprecated, use on instead.

delegate(selector, type, function(e){ ... }) ⇒ self
delegate(selector, { type: handler, type2: handler2, ... }) ⇒ self

Attach an event handler that is only triggered when the event originated from a node that matches a selector.

die 🦄🔨

Deprecated, use off instead.

die(type, function(e){ ... }) ⇒ self
die({ type: handler, type2: handler2, ... }) ⇒ self

Detach event handler added by live.

event.isDefaultPrevented v1.1+

event.isDefaultPrevented() ⇒ boolean

Returns true if preventDefault() was called for this event instance. This serves as a cross-platform alternative to the native defaultPrevented property which is missing or unreliable in some browsers.

// trigger a custom event and check whether it was cancelled
var event = $.Event('custom')
element.trigger(event)
event.isDefaultPrevented()

event.isImmediatePropagationStopped v1.1+

event.isImmediatePropagationStopped() ⇒ boolean

Returns true if stopImmediatePropagation() was called for this event instance. Zepto implements the native method in browsers that don’t support it (e.g. old versions of Android).

event.isPropagationStopped v1.1+

event.isPropagationStopped() ⇒ boolean

Returns true if stopPropagation() was called for this event instance.

live 🦄🔨

Deprecated, use on instead.

live(type, function(e){ ... }) ⇒ self
live({ type: handler, type2: handler2, ... }) ⇒ self

Like delegate where the selector is taken from the current collection.

off

off(type, [selector], function(e){ ... }) ⇒ self
off({ type: handler, type2: handler2, ... }, [selector]) ⇒ self
off(type, [selector]) ⇒ self
off() ⇒ self

Detach event handlers added with on. To detach a specific event handler, the same function must be passed that was used for on(). Otherwise, just calling this method with an event type will detach all handlers of that type. When called without arguments, it detaches all event handlers registered on current elements.

on

on(type, [selector], function(e){ ... }) ⇒ self
on(type, [selector], [data], function(e){ ... }) ⇒ self [v1.1]
on({ type: handler, type2: handler2, ... }, [selector]) ⇒ self
on({ type: handler, type2: handler2, ... }, [selector], [data]) ⇒ self [v1.1]

Add event handlers to the elements in collection. Multiple event types can be passed in a space-separated string, or as an object where event types are keys and handlers are values. If a CSS selector is given, the handler function will only be called when an event originates from an element that matches the selector.

If the data argument is given, this value will be made available as the event.data property during the execution of the event handler.

Event handlers are executed in the context of the element to which the handler is attached, or the matching element in case a selector is provided. When an event handler returns false, preventDefault() and stopPropagation() is called for the current event, preventing the default browser action such as following links.

If false is passed as argument to this method in place of the callback function, it’s equivalent to passing a function that returns false.

var elem = $('#content')
// observe all clicks inside #content:
elem.on('click', function(e){ ... })
// observe clicks inside navigation links in #content
elem.on('click', 'nav a', function(e){ ... })
// all clicks inside links in the document
$(document).on('click', 'a', function(e){ ... })
// disable following any navigation link on the page
$(document).on('click', 'nav a', false)

one

one(type, [selector], function(e){ ... }) ⇒ self
one(type, [selector], [data], function(e){ ... }) ⇒ self [v1.1]
one({ type: handler, type2: handler2, ... }, [selector]) ⇒ self
one({ type: handler, type2: handler2, ... }, [selector], [data]) ⇒ self [v1.1]

Adds an event handler that removes itself the first time it runs, ensuring that the handler only fires once. See .on() for the explanation of selector and data arguments.

trigger

trigger(event, [args]) ⇒ self

Trigger the specified event on elements of the collection. Event can either be a string type, or a full event object obtained with $.Event. If an args array is given, it is passed as additional arguments to event handlers.

// add a handler for a custom event
$(document).on('mylib:change', function(e, from, to){
  console.log('change on %o with data %s, %s', e.target, from, to)
})
// trigger the custom event
$(document.body).trigger('mylib:change', ['one', 'two'])

Zepto only supports triggering events on DOM elements.

triggerHandler

triggerHandler(event, [args]) ⇒ self

Like trigger, but triggers only event handlers on current elements and doesn’t bubble.

unbind 🦄🔨

Deprecated, use off instead.

unbind(type, function(e){ ... }) ⇒ self
unbind({ type: handler, type2: handler2, ... }) ⇒ self

Detach event handler added with bind.

undelegate 🦄🔨

Deprecated, use off instead.

undelegate(selector, type, function(e){ ... }) ⇒ self
undelegate(selector, { type: handler, type2: handler2, ... }) ⇒ self

Detach event handler added with delegate.


Ajax 请求

$.ajax

$.ajax(options) ⇒ XMLHttpRequest

Perform an Ajax request. It can be to a local resource, or cross-domain via HTTP access control support in browsers or JSONP.

Options:

  • type (default: “GET”): HTTP request method (“GET”, “POST”, or other)
  • url (default: current URL): URL to which the request is made
  • data (default: none): data for the request; for GET requests it is appended to query string of the URL. Non-string objects will get serialized with $.param
  • processData (default: true): whether to automatically serialize data for non-GET requests to string
  • contentType (default: “application/x-www-form-urlencoded”): the Content-Type of the data being posted to the server (this can also be set via headers). Pass false to skip setting the default value.
  • mimeType (default: none): override the MIME type of the response. v1.1+
  • dataType (default: none): response type to expect from the server. One of json, jsonp, script, xml, html, or text.
  • jsonp (default: “callback”): the name of the JSONP callback query parameter
  • jsonpCallback (default: “jsonp{N}”): the string (or a function that returns) name of the global JSONP callback function. Set this to enable browser caching. v1.1+
  • timeout (default: 0): request timeout in milliseconds, 0 for no timeout
  • headers: object of additional HTTP headers for the Ajax request
  • async (default: true): set to false to issue a synchronous (blocking) request
  • global (default: true): trigger global Ajax events on this request
  • context (default: window): context to execute callbacks in
  • traditional (default: false): activate traditional (shallow) serialization of data parameters with $.param
  • cache (default: true): whether the browser should be allowed to cache GET responses. Since v1.1.4, the default is false for dataType: "script" or jsonp.
  • xhrFields (default: none): an object containing properties to be copied over verbatim to the XMLHttpRequest instance. v1.1+
  • username & password (default: none): HTTP Basic authentication credentials. v1.1+

If the URL contains =? or dataType is “jsonp”, the request is performed by injecting a <script> tag instead of using XMLHttpRequest (see JSONP). This has the limitation of contentType, dataType, headers, and async not being supported.

Ajax callbacks

You can specify the following callback functions, which are given in order of execution:

  1. beforeSend(xhr, settings): before the request is sent. Provides access to the xhr object and allows changing the settings. Return false from the function to cancel the request

  2. success(data, status, xhr): when request succeeds

  3. error(xhr, errorType, error): if there is an error (timeout, parse error, or status code not in HTTP 2xx)

  4. complete(xhr, status): after the request is complete, regardless of error or success

Promise callback interface v1.1+

If the optional modules “callbacks” and “deferred” are loaded, the XHR object returned from $.ajax() calls implements a promise interface for adding callbacks by chaining:

xhr.done(function(data, status, xhr){ ... })
xhr.fail(function(xhr, errorType, error){ ... })
xhr.always(function(){ ... })
xhr.then(function(){ ... })

These methods supersede the success, error, and complete callback options.

Ajax events

These events are fired during the lifecycle of an Ajax request performed with the default setting of global: true:

  1. ajaxStart (global): fired if no other Ajax requests are currently active

  2. ajaxBeforeSend (xhr, options): before sending the request; can be cancelled

  3. ajaxSend (xhr, options): like ajaxBeforeSend, but not cancellable

  4. ajaxSuccess (xhr, options, data): when the response is success

  5. ajaxError (xhr, options, error): when there was an error

  6. ajaxComplete (xhr, options): after request has completed, regardless of error or success

  7. ajaxStop (global): fired if this was the last active Ajax request

By default, Ajax events are fired on the document object. However, if the context of a request is a DOM node, the events are fired on that node and will bubble up the DOM. The only exceptions to this are the global events ajaxStart & ajaxStop.

$(document).on('ajaxBeforeSend', function(e, xhr, options){
  // This gets fired for every Ajax request performed on the page.
  // The xhr object and $.ajax() options are available for editing.
  // Return false to cancel this request.
})

$.ajax({
  type: 'GET',
  url: '/projects',
  // data to be added to query string:
  data: { name: 'Zepto.js' },
  // type of data we are expecting in return:
  dataType: 'json',
  timeout: 300,
  context: $('body'),
  success: function(data){
    // Supposing this JSON payload was received:
    //   {"project": {"id": 42, "html": "<div>..." }}
    // append the HTML to context object.
    this.append(data.project.html)
  },
  error: function(xhr, type){
    alert('Ajax error!')
  }
})

// post a JSON payload:
$.ajax({
  type: 'POST',
  url: '/projects',
  // post payload:
  data: JSON.stringify({ name: 'Zepto.js' }),
  contentType: 'application/json'
})

$.ajaxJSONP 🦄🔨

Deprecated, use $.ajax instead.

$.ajaxJSONP(options) ⇒ mock XMLHttpRequest

Perform a JSONP request to fetch data from another domain.

This method has no advantages over $.ajax and should not be used.

$.ajaxSettings

Object containing the default settings for Ajax requests. Most settings are described in $.ajax. The ones that are useful when set globally are:

  • timeout (default: 0): set to a non-zero value to specify a default timeout for Ajax requests in milliseconds
  • global (default: true): set to false to prevent firing Ajax events
  • xhr (default: XMLHttpRequest factory): set to a function that returns instances of XMLHttpRequest (or a compatible object)
  • accepts: MIME types to request from the server for specific dataType values:
    • script: “text/javascript, application/javascript”
    • json: “application/json”
    • xml: “application/xml, text/xml”
    • html: “text/html”
    • text: “text/plain”

$.get

$.get(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
$.get(url, [data], [function(data, status, xhr){ ... }], [dataType]) ⇒ XMLHttpRequest [v1.0]

Perform an Ajax GET request. This is a shortcut for the $.ajax method.

$.get('/whatevs.html', function(response){
  $(document.body).append(response)
})

$.getJSON

$.getJSON(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
$.getJSON(url, [data], function(data, status, xhr){ ... }) ⇒ XMLHttpRequest [v1.0]

Get JSON data via Ajax GET request. This is a shortcut for the $.ajax method.

$.getJSON('/awesome.json', function(data){
  console.log(data)
})

// fetch data from another domain with JSONP
$.getJSON('//example.com/awesome.json?callback=?', function(remoteData){
  console.log(remoteData)
})

$.param

$.param(object, [shallow]) ⇒ string
$.param(array) ⇒ string

Serialize an object to a URL-encoded string representation for use in Ajax request query strings and post data. If shallow is set, nested objects are not serialized and nested array values won’t use square brackets on their keys.

If any of the individual value objects is a function instead of a string, the function will get invoked and its return value will be what gets serialized.

This method accepts an array in serializeArray format, where each item has “name” and “value” properties.

$.param({ foo: { one: 1, two: 2 }})
//=> "foo[one]=1&foo[two]=2)"

$.param({ ids: [1,2,3] })
//=> "ids[]=1&ids[]=2&ids[]=3"

$.param({ ids: [1,2,3] }, true)
//=> "ids=1&ids=2&ids=3"

$.param({ foo: 'bar', nested: { will: 'not be ignored' }})
//=> "foo=bar&nested[will]=not+be+ignored"

$.param({ foo: 'bar', nested: { will: 'be ignored' }}, true)
//=> "foo=bar&nested=[object+Object]"

$.param({ id: function(){ return 1 + 2 } })
//=> "id=3"

$.post

$.post(url, [data], function(data, status, xhr){ ... }, [dataType]) ⇒ XMLHttpRequest

Perform an Ajax POST request. This is a shortcut for the $.ajax method.

$.post('/create', { sample: 'payload' }, function(response){
  // process response
})

data can also be a string:

$.post('/create', $('#some_form').serialize(), function(response){
  // ...
})

load

load(url, function(data, status, xhr){ ... }) ⇒ self

Set the html contents of the current collection to the result of a GET Ajax call to the given URL. Optionally, a CSS selector can be specified in the URL, like so, to use only the HTML content matching the selector for updating the collection:

$('#some_element').load('/foo.html #bar')

If no CSS selector is given, the complete response text is used instead.

Note that any JavaScript blocks found are only executed in case no selector is given.


表单方法

serialize

serialize() ⇒ string

Serialize form values to an URL-encoded string for use in Ajax post requests.

serializeArray

serializeArray() ⇒ array

Serialize form into an array of objects with name and value properties. Disabled form controls, buttons, and unchecked radio buttons/checkboxes are skipped. The result doesn’t include data from file inputs.

$('form').serializeArray()
//=> [{ name: 'size', value: 'micro' },
//    { name: 'name', value: 'Zepto' }]

submit

submit() ⇒ self
submit(function(e){ ... }) ⇒ self

Trigger or attach a handler for the submit event. When no function given, trigger the “submit” event on the current form and have it perform its submit action unless preventDefault() was called for the event.

When a function is given, this simply attaches it as a handler for the “submit” event on current elements.


Effects

$.fx

Global settings for animations:

  • $.fx.off (default false in browsers that support CSS transitions): set to true to disable all animate() transitions.

  • $.fx.speeds: an object with duration settings for animations:

    • _default (400 ms)
    • fast (200 ms)
    • slow (600 ms)

    Change existing values or add new properties to affect animations that use a string for setting duration.

animate

animate(properties, [duration, [easing, [function(){ ... }]]]) ⇒ self
animate(properties, { duration: msec, easing: type, complete: fn }) ⇒ self
animate(animationName, { ... }) ⇒ self

Smoothly transition CSS properties of elements in the current collection.

  • properties: object that holds CSS values to animate to; or CSS keyframe animation name
  • duration (default 400): duration in milliseconds, or a string:
    • fast (200 ms)
    • slow (600 ms)
    • any custom property of $.fx.speeds
  • easing (default linear): specifies the type of animation easing to use, one of:
  • complete: callback function for when the animation finishes
  • delay: transition delay in milliseconds v1.1+

Zepto also supports the following CSS transform properties:

  • translate(X|Y|Z|3d)
  • rotate(X|Y|Z|3d)
  • scale(X|Y|Z)
  • matrix(3d)
  • perspective
  • skew(X|Y)

If the duration is 0 or $.fx.off is true (default in a browser that doesn’t support CSS transitions), animations will not be executed; instead the target values will take effect instantly. Similarly, when the target CSS properties match the current state of the element, there will be no animation and the complete function won’t be called.

If the first argument is a string instead of object, it is taken as a CSS keyframe animation name.

$("#some_element").animate({
  opacity: 0.25, left: '50px',
  color: '#abcdef',
  rotateZ: '45deg', translate3d: '0,10px,0'
}, 500, 'ease-out')

Zepto exclusively uses CSS transitions for effects and animation. jQuery easings are not supported. jQuery’s syntax for relative changes (=+10px) is not supported. See the spec for a list of animatable properties. Browser support may vary, so be sure to test in all browsers you want to support.


Touch

Touch events

The “touch” module adds the following events, which can be used with on and off:

  • tap — fires when the element is tapped.
  • singleTap and doubleTap — this pair of events can be used to detect both single and double taps on the same element (if you don’t need double tap detection, use tap instead).
  • longTap — fires when an element is tapped and the finger is held down for more than 750ms.
  • swipe, swipeLeft, swipeRight, swipeUp, swipeDown — fires when an element is swiped (optionally in the given direction)

All these events are also available via shortcut methods on any Zepto collection.

<style>.delete { display: none; }</style>

<ul id=items>
  <li>List item 1 <span class=delete>DELETE</span></li>
  <li>List item 2 <span class=delete>DELETE</span></li>
</ul>

<script>
// show delete buttons on swipe
$('#items li').swipe(function(){
  $('.delete').hide()
  $('.delete', this).show()
})

// delete row on tapping delete button
$('.delete').tap(function(){
  $(this).parent('li').remove()
})
</script>

Change Log

查看 Github 上的 更新记录


致谢 & 感谢

A big Thank-You goes out to all of our awesome Zepto.js contributors. May you all forever bask in glory.

The Zepto API is based on jQuery's Core API, which is released under the MIT license.

This documentation is based on the layout of the Backbone.js documentation, which is released under the MIT license.

© 2010-2018 Thomas Fuchs, Freckle Online Time Tracking
Zepto and this documentation is released under the terms of the MIT license.