Zepto.js

Zepto是一个轻量级的针对现代高级浏览器的JavaScript库, 它与jquery有着类似的api。 如果你会用jquery,那么你也会用zepto。

设计的目的是提供jquery的类似的APIs,但并不是100%覆盖jquery为目的。zepto设计的目的是有一个5-10k的通用库、下载并执行快、有一个熟悉通用的API,所以你能把你主要的精力放到应用开发上。

Zepto 是一款开源软件,它可以被开发者和商业发布。 MIT license.

本API原文地址:http://zeptojs.com/

本文翻译问题请联系:yaotaiyang

下载 Zepto

默认的构建包括以下模块:
Core, Ajax, Event, Form, Effects, Polyfill, and Detect.

还有更多的模块; 所以可用模块链接在此 README.

用一个script标签引入Zepto到你的页面的底部:

...
    </body>
    <script src=zepto.min.js></script>
    </html>

如果你需要兼容ie浏览器,你可以用回jquery。 需要注意ie10以后不再支持条件注释(为了提高与HTML5 的可互操作性和兼容性,Internet Explorer 10 标准模式和Quirks 模式中删除了对条件注释的支持),因此,我们建议以下的document.write方法:

<script>
    document.write('<script src=' +
    ('__proto__' in {} ? 'zepto' : 'jquery') +
    '.js><\/script>')
    </script>

目标平台

桌面浏览器

移动端浏览器

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

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

总之,除了ie浏览器外,Zepto希望在所有的现代浏览器中作为一种基础环境来使用。

手动建立Zepto

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

关于如何建立Zepto的the README,包含运行测试和补丁。.

创建插件

可以通过添加方法作为$.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)

为了更好开始开发插件,先看下source of Zepto's core module,并确认读过coding style guidelines


核心方法

$()

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

通过执行css选择器包装dom节点,创建元素或者从一个html片段来创建一个Zepto对象。

Zepto集合是一个类似数组的对象,它具有链式方法来操作它指向的dom,除了$对象上的直接方法外(如$.extend),文档对象中的所有方法都是集合方法。

如果选择器中存在content参数(css选择器,dom,或者Zepto集合对象),那么只在所给的节点背景下进行css选择器;这个功能有点像使用$(context).find(selector)

可以通过一个html字符串片段来创建一个dom节点。也可以通过给定一组属性映射来创建节点。最快的创建但元素,使用<div><div/>形式。

当一个函数附加在 DOMContentLoaded 事件的处理流程中。如果页面已经加载完毕,这个方法将会立即被执行。

$('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 扩展,但是可以选的“selector”模块有限提供支持,如一些常用的伪选择器,可以与现有的代码或插件兼容执行。

$.camelCase v1.0+

$.camelCase(string) ⇒ string
  

将一组字符串变成“骆驼”命名法的新字符串,如果该字符已经是“骆驼”命名法,则不变化。

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

$.contains v1.0+

$.contains(parent, node) ⇒ boolean
  

检查父节点是否包含给定的dom节点,如果两者相同,则返回 false

$.each

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

遍历数组元素或以key-value值对方式遍历对象。回调函数返回 false 时停止遍历。

$.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]
  

通过源对象扩展目标对象的属性,源对象属性将覆盖目标对象属性。

默认情况下为,复制为浅复制。如果第一个参数为true表示深度复制。

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

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

$.fn

Zepto.fn是一个对象,它拥有Zepto对象上所有可用的方法。如 addClass()attr(),和其它方法。在这个对象添加一个方法,所有的Zepto对象上都能用到该方法。

这里有一个实现 empty() 方法的例子:

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

$.grep v1.0+

$.grep(items, function(item){ ... }) ⇒ array
$.grep([1,2,3], function(){
  return item > 1
});
 //=>[2,3] 
  

获取一个新数组,新数组只包含回调函数中返回 ture 的数组项。

$.inArray v1.0+

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

搜索数组中指定值并返回它的索引(如果没有找到则返回-1)。

[fromIndex] 参数可选,表示从哪个索引值开始向后查找。

$.inArray("abc",["bcd","abc","edf","aaa"]);
 //=>1

$.inArray("abc",["bcd","abc","edf","aaa"],1);
 //=>1

$.inArray("abc",["bcd","abc","edf","aaa"],2);
 //=>-1
     

$.isArray

$.isArray(object) ⇒ boolean
  

如果object是array,则返回ture。

$.isFunction

$.isFunction(object) ⇒ boolean
  

如果object是function,则返回ture。

$.isPlainObject v1.0+

$.isPlainObject(object) ⇒ boolean
  

测试对象是否是纯粹的对象(通过 "{}" 或者 "new Object" 创建的),如果是,则返回true。

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

$.isWindow v1.0+

$.isWindow(object) ⇒ boolean
  

确定参数是否为一个窗口(window对象),如果是则返回true。

这在处理iframe时非常有用,因为每个iframe都有它们自己的window对象,使用常规方法obj==window校验这些objects的时候会失败。

$.map

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

通过遍历集合中的元素,通过函数返回一个新的数组,null and undefined 将被过滤掉。

$.map([1,2,3,4,5],function(item,index){
        if(item>1){return item*item;}
}); 
// =>[4, 9, 16, 25]

$.map({"yao":1,"tai":2,"yang":3},function(item,index){
        if(item>1){return item*item;}
}); 
// =>[4, 9]

$.parseJSON v1.0+

$.parseJSON(string) ⇒ object
  

类似本地JSON.parse 方法,接受一个标准格式的 JSON 字符串,并返回解析后的 JavaScript 对象。

$.trim v1.0+

$.trim(string) ⇒ string
  

删除字符串开始和末尾的空白符。类似String.prototype.trim()。

$.type v1.0+

$.type(object) ⇒ string
  

获取JavaScript 对象的类型。可能的类型有: null undefined boolean number string function array date regexp object error

对于其它对象,它只是简单报告为“object”,如果你想知道一个对象是否是一个javascript普通对象,使用 isPlainObject

add

add(selector, [context]) ⇒ self
  

添加元素到匹配的元素集合。如果content参数存在,只在content中进行查找,否则在document中查找。

<ul>    
    <li>list item 1</li>    
    <li>list item 2</li>    
    <li>list item 3</li>  
</ul>  
<p>a paragraph</p>

<script type="text/javascript">
	$('li').add('p').css('background-color', 'red');
</script>

 

addClass

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

为每个匹配的元素添加指定的class类名。多个class类名通过空格f分隔。

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参数,则读取Zepto对象第集合一个元素的属性值。当给定了value参数。则设置Zepto对象集合中所有元素所有元素的属性值。当value参数为null,那么这个属性将被移除(类似removeAttr),多个属性能以通过对象值对的方式进行设置。

要读取dom的属性如 checkedselected, 使用 prop

var form = $('form')
        form.attr('action')             //=> read value
        form.attr('action', '/create')  //=> set value
        form.attr('action', null)       //=> remove attribute

        // multiple attributes:
        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选择器的元素。

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

clone v1.0+

clone() ⇒ collection
  

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

此方法不会有数据和事件处理程序复制到新的元素。这点和jquery中利用一个参数来确定是否复制数据和事件处理不相同。

closest

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

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

 

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

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

concat

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

添加元素到一个Zepto对象集合形成一个新数组。如果参数是一个数组,那么这个数组中的元素将会合并到Zepto对象集合中。

这是一个Zepto提供的方法,不是jquey的API 。

contents v1.0+

contents() ⇒ collection
  

获得每个匹配元素集合元素的子元素,包括文字和注释节点。.contents()和.children()方法类似,只不过前者包括文本节点以及jQuery对象中产生的HTML元素。

css

css(property) ⇒ value
      css(property, value) ⇒ self
      css({ property: value, property2: value2, ... }) ⇒ self
  

读取或设置dom元素的css属性。当value参数不存在的时候,返回Zepto对象集合中第一个元素的css属性。当value参数存在时,设置Zepto对象集合中每一个元素的对应css属性。多条css属性可以利用对象值对的方式进行设置。

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

var elem = $('h1')
        elem.css('background-color')          // read property
        elem.css('background-color', '#369')  // set property
        elem.css('background-color', '')      // remove property

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

data

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

读取或写入dom的 data-* 属性。行为有点像 attr ,但是属性名称前面加上 data-

当读取属性值时,会有下列转换:v1.0+

  • “true”, “false”, and “null” 被转换为相应的类型;
  • 数字值转换为实际的数字类型;
  • JSON值将会被解析,如果它是有效的JSON;
  • 其它的一切作为字符串返回。

    Zepto 基本实现`data()`只能存储字符串。如果你要存储任意对象,请引入可选的“data”模块到你构建的Zepto中。

each

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

遍历一个Zepto集合对象,为每一个匹配元素执行一个函数。this关键字指向当前item(作为函数的第二个参数传递)。如果函数返回 false,遍历结束。

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

empty

empty() ⇒ self
  

从Zepto对象集合中移除所有的dom子节点。

eq

eq(index) ⇒ collection
  

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

$('li').eq(0)   //=> only the first list item
        $('li').eq(-1)  //=> only the last list item
    

filter

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

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

与此相反的功能,查看not.

find

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

获得当前Zepto集合对象内查找符合css选择器的每个元素的后代。

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

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

first

first() ⇒ collection
  

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

$('form').first()
    

forEach

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

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

这是一个Zepto提供的方法,不是jquery的API。

get

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

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

var elements = $('h2')
        elements.get()   //=> get all headings as an array
        elements.get(0)  //=> get first heading node
    

has v1.0+

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

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

$('ol > li').has('a[href]')
        //=> get only LI elements that contain links
    

hasClass

hasClass(name) ⇒ boolean
  

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

<ul>    
    <li>list item 1</li>    
    <li class="yaotaiyang">list item 2</li>    
    <li>list item 3</li>  
</ul>  
<p>a paragraph</p>

<script type="text/javascript">
	$("li").hasClass("yaotaiyang");
	//=> true
</script>

height

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

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

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

hide

hide() ⇒ self
  

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

Hide elements in this collection by setting their display CSS property to none.

html

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

获取或设置Zepto对象集合中元素的HTML内容。当content参数没有给定时,返回IZepto对象集合中第一个元素的innerHtm。当content参数给定时。用其替换Zepto对象集合中每个元素的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

获取一个元素的位置。当elemen参数没有给出时,返回当前元素在兄弟节点中的位置。当element参数给出时,返回它在当前Zepto对象集合中的位置。如果没有该元素,则返回-1。

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

indexOf

indexOf(element, [fromIndex]) ⇒ number
  

在当前Zepto中获取一个元素的位置。如果formindex参数给出,从该位置往后查找,返回基于0的位置,如果没找到,则返回-1。index 方法是基于这个方法实现的。

这是一个Zepto的方法,不是jquer的api。

insertAfter

insertAfter(target) ⇒ self

插入Zepto对象集合中的元素到指定的每个元素后面的dom中。这个有点像 after,但是使用方式相反。

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

insertBefore

insertBefore(target) ⇒ self

插入Zepto对象集合中的元素到指定的每个元素前面的dom中。这个有点像 before,但是使用方式相反。

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

is

is(selector) ⇒ boolean
  

判断当前Zepto元素集合中的第一个元素是否符css选择器。对于基础支持jquery的非标准选择器类似: :visible包含在可选的“selector”模块中。

jQuery CSS extensions 不被支持。 选择“selector”模块仅仅能支持有限几个最常用的方式。

last

last() ⇒ collection

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

$('li').last()
    

map

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

遍历Zepto对象集合中的所有元素。通过遍历函数返回值形成一个新的集合对象。在遍历函数中this关键之指向当前循环的item(遍历函数中的第二个参数)。遍历中返回 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]

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

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

not

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

过滤当前Zepto对象集合,获取一个新的Zepto对象集合,它里面的元素不能匹配css选择器。如果另一个参数为Zepto集合对象,那么返回的新Zepto对象中的元素都不包含在该参数对象中。如果参数是一个函数。仅仅包含函数执行为false值得时候的元素,函数的 this 关键字指向当前循环元素。

与它相反的功能,查看 filter.

offset

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

获得当前元素相对于document的位置。返回一个对象含有: top, left, widthheight

当给定一个对象属性lefttop使用这些值来相对于document对每一个元素进行定位。

offsetParent v1.0+

offsetParent() ⇒ collection
  

找到第一个定位过的祖先元素,在ccs中意味着它的position 值为“relative”, “absolute” or “fixed”

parent

parent([selector]) ⇒ collection

获取Zepto对象集合中每个元素的直接父元素。如果css选择器参数给出。过滤出符合条件的元素。

parents

parents([selector]) ⇒ collection

获取Zepto对象集合每个元素所有的祖先元素。如果css选择器参数给出,过滤出符合条件的元素。

如果想获取直接父级元素,使用 parent。如果只想获取到第一个符合css选择器的元素,使用closest

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

pluck

pluck(property) ⇒ array
  

获取Zepto对象集合中每一个元素的属性值。返回值为 nullundefined值得过滤掉。

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

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

这是一个Zepto的方法,不是jquery的api

position v1.0+

position() ⇒ object
  

获取Zepto对象集合中第一个元素的位置。相对于 offsetParent。当绝对定位的一个素靠近另一个元素的时候,这个方法是有用的。

返回一个的对象有这些属性: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
  

将参数内容插入到每个匹配元素的前面(元素内部)。插入d的元素可以试html字符串片段,一个dom节点,或者一个节点的数组。

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

prependTo

prependTo(target) ⇒ self
  

将所有元素插入到目标前面(元素内)。这有点像prepend,但是是相反的方式。

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

prev

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

获取Zepto对象集合中每一个元素的前一个兄弟节点,通过选择器来进行过滤。

prop v1.0+

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

读取或设置dom元素的属性值。它在读取属性值的情况下优先于 attr,因为这些属性值会因为用户的交互发生改变,如checked and selected

<input class="taiyang" id="check1" type="checkbox" checked="checked">
<input class="yaotaiyang" id="check2" type="checkbox"> <script type="text/javascript"> $("#check1").attr("checked"); //=> "checked" $("#check1").prop("checked"); //=> "true" $("#check2").attr("checked"); //=> "false" $("#check2").prop("checked"); //=> "false" $("input[type='checkbox']").prop("type",function(index,oldvalue){ console.log(index+"|"+oldvalue); }); //=> 0|checkbox //=> 1|checkbox $("input[type='checkbox']").prop("className",function(index,oldvalue){ console.log(index+"|"+oldvalue); }); //=> 0|taiyang //=> 1|yaotaiyang </script>

 

push

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

添加元素到当前Zepto对象的最后。

这是一个zepto的方法,不是jquery的api

ready

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

添加一个事件侦听器,当页面dom加载完毕 “DOMContentLoaded” 事件触发时触发。建议使用 $()来代替这种用法。

reduce

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

Array.reduce有相同的用法,遍历当前Zepto对象集合。memo是函数上次的返回值。迭代进行遍历。

这是一个zepto的方法,不是jquery的api

remove

remove() ⇒ self
  

移出当前Zepto对象中的元素。有效的从dom中移除。

removeAttr

removeAttr(name) ⇒ self
  

移动当前Zepto对象集合中所有元素的指定属性。

removeClass

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

移动当前Zepto对象集合中所有元素的指定class。如果name参数未给出。将移出所有的class。多个class参数名称可以利用空格分隔。下例移除了两个class。

<input class="taiyang yueliang" id="check1" type="checkbox" checked="checked">
<input class="yaotaiyang" id="check2" type="checkbox"> <script type="text/javascript"> $("#check1").removeClass("taiyang yueliang") //=>[<input class id="check1" type="checkbox" checked="checked">] </script>

replaceWith

replaceWith(content) ⇒ self
  

用提供的内容替换所有匹配的元素。(包含元素本身)。content参数可以为 before中描述的类型。

scrollTop v1.0+

scrollTop() ⇒ number
  

获取页面上的滚动元素或者整个窗口已经滚动的像素值。

show

show() ⇒ self

恢复Zepto对象集合中每个元素默认的“display”值。如果你用 hide将元素隐藏,用该属性可以将其显示。相当于干掉了display:none

siblings

siblings([selector]) ⇒ collection
  

获取Zepto集合对象所有统计节点。如果css选择器参数给出。过滤出符合选择器的元素。

size

size() ⇒ number

获取Zepto对象集合中元素的数量。

slice

slice(start, [end]) ⇒ array

array中提取的方法。从start开始,如果end 指出。提取不包含end位置的元素。

text

text() ⇒ string
      text(content) ⇒ self
  

获取或者设置所有Zepto对象的文本内容。当content参数未给出。返回当前Zepto对象集合中第一个元素的文本内容(包含子节点中的文本内容)。当content参数给出,使用它替换Zepto对象集合中所有元素的文本内容。它有待点似 html,与它不同的是它不能用来获取或设置 HTML。

toggle

toggle([setting]) ⇒ self

显示或隐藏匹配元素。如果 setting为true,相当于show 法。如果setting为false。相当于 hide方法。

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

toggleClass

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

在匹配的元素集合中的每个元素上添加或删除一个或多个样式类。如果cclass的名称存在则删除它,如果不存在,就添加它。如果 setting的值为真,这个功能类似于 addClass,如果为假,这个功能类似与 removeClass

unwrap

unwrap() ⇒ self

将匹配元素的父级元素删除,保留自身(和兄弟元素,如果存在)在原来的位置。

$(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
  

获取或设置比哦单元素的值。当value参数不存在。返回第一个元素的值。如果是<select multiple>标签,则返回一个数组。

width

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

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

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

wrap

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

在每个匹配的元素外层包上一个html元素。structure参数可以是一个单独的元素或者一些嵌套的元素。也可以是一个html字符串片段或者dom节点。还可以是一个生成用来包元素的回调函数,这个函数返回前两种类型的包裹片段。

需要提醒的是:该方法对于dom中的节点有着很好的支持。如果将wrap() 用在一个新的元素上,然后再将结果插入到document中,此时该方法无效。

// 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

在所有匹配元素外面包一层HTML结构。

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

wrapInner

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

在匹配元素里的内容外包一层结构。

    // 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>')
以下为原始html:
		<div class="yaotaiyang">
			<div class="taiyang">yao</div>
			<div class="taiyang">yao</div>
		</div>

通过:$('.taiyang).wrapInner('<div class="new" />');

得到:
		<div class="yaotaiyang">
			<div class="taiyang"><div class="new">yao</div></div>
			<div class="taiyang"><div class="new">yao</div></div>
		</div>    

检测方法

Detect module

 

该检测方法可以再不同的环境中微调你的站点或者应用程序,并帮助你识别手机和平板;以及不同的浏览器和操作系统。

// 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.touchpad
        $.os.kindle

        // specific browser
        $.browser.chrome
        $.browser.firefox
        $.browser.silk
        $.browser.playbook

        // 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

创建并初始化一个指定的dom事件。如果properties参数给出,使用它来扩展出新的事件对象。默认情况下,事件被设置为冒泡方式;这个可以通过设置bubblesfalse来关闭。

初始化的功能可以使用 trigger来触发。

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

$.proxy v1.0+

$.proxy(fn, context) ⇒ function
      $.proxy(context, property) ⇒ function
  

接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文语境,新函数中this指向context参数。另外一种形式,原始的function是context对像的方法。

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));

var obj = {name: "yaotaiyang",
		test: function() {
			alert( this.name );      
			$("#test").unbind("click", obj.test); 
		}
		};    
$("#test").click( jQuery.proxy( obj, "test" ));
    

bind 🐶🔫

Deprecated, use on instead.

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

为一个元素绑定一个处理事件。

delegate 🐶🔫

Deprecated, use on instead.

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

基于一组特定的根元素为所有选择器匹配的元素附加一个处理事件,匹配的元素可能现在或将来才创建。

die 🐶🔫

Deprecated, use off instead.

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

删除通过 live 添加的事件。

live 🐶🔫

Deprecated, use on instead.

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

类似delegate,其中selector参数为当前Zepto集合对象。

off

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

移除通过 on 注册的事件(用bind或者用on注册的事件)。如果没有参数,将移出当前元素上所有的注册事件。

off(type, [selector], function(e){ ... }) ⇒ self

如果selector存在,则相当于delegate。
$("ul").on("click","li",function(){alert("yaotaiyang")});
以上代码相当于将li的事件代理到ul上。后续添加的li也能拥有以上方法。该事件可以通过undelegate来移除。
$("ul").undelegate();
也可用:$("ul").off();

如果selector参数不存在。则相当于bind。
$("li").on("click",function(){alert("yaotaiyang")});
该事件可以通过unbind来移除。
$("li").unbind("click");
也可以用off()来移除:$("li").off();

on方法继集成bind和delegate方法。

on

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

添加事件到Zepto对象集合上。多个事件可以通过空格的字符串方式添加。或者以事件类型、函数对象的 方式。如果css选择器给出,事件的对象满足选择器条件时。事件才会被触发。

事件处理程序在触发事件元素或者css选择器匹配的元素的上下文中执行(this指向触发事件的元素)。

当事件处理程序返回false, 或调用preventDefault(),浏览器的默认事件将会被阻止。

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){ ... })
    
on(type, [selector], function(e){ ... }) ⇒ self

如果selector存在,则相当于delegate。
$("ul").on("click","li",function(){alert("yaotaiyang")});
以上代码相当于将li的事件代理到ul上。后续添加的li也能拥有以上方法。该事件可以通过undelegate来移除。
$("ul").undelegate();
也可用:$("ul").off();

如果selector参数不存在。则相当于bind。
$("li").on("click",function(){alert("yaotaiyang")});
该事件可以通过unbind来移除。
$("li").unbind("click");
也可以用off()来移除:$("li").off();

on方法继集成bind和delegate方法。

one

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

添加一个处理事件到元素。处理函数在每个元素上最多执行一次。

trigger

trigger(event, [data])
  

在Zepto对象集合的元素上触发指定的事件。事件可以是一个字符串,也可以是一个 $.Event 对象。如果data参数存在,它会作为参数传递给事件函数。

// 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仅仅支持在dom元素上触发事件。

triggerHandler

triggerHandler(event, [data]) ⇒ self

trigger,它只触发事件,但不冒泡。

比如你再一个input上如果使用该方法。

		$("input").triggerHandler('focus');
        // 此时input上的focus事件触发,但是input不会聚焦
		$("input").trigger('focus');
        // 此时input上的focus事件触发,input聚焦

unbind 🐶🔫

Deprecated, use off instead.

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

移除通过 bind 注册的事件。

undelegate 🐶🔫

Deprecated, use off instead.

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

移除通过delegate 注册的事件。


Ajax请求

$.ajax

$.ajax(options) ⇒ XMLHttpRequest 

执行Ajax请求。请求地址可以是本地的或者跨域的,在支持的浏览器中通过 HTTP access control或者通过 JSONP来完成。

参数:

  • type (默认: “GET”):请求方法 (“GET”, “POST”, or other)
  • url (默认: 当前地址):发送请求的地址
  • data (默认:none):发送到服务器的数据;如果是get请求,它会自动被作为参数拼接到url上。非String对象将通过 $.param 得到序列化字符串。
  • processData (默认: true): 对于非Get请求。是否自动将 data 转换为字符串。
  • contentType (默认: “application/x-www-form-urlencoded”): 发送信息至服务器时内容编码类型。 (这也可以通过设置headers headers)。通过设置 false 跳过设置默认值。
  • dataType (默认: none):预期服务器返回的数据类型(“json”, “jsonp”, “xml”, “html”, or “text”)
  • timeout (默认: 0): 设置请求超时时间(毫秒),0表示不超时。
  • headers (默认:{}): 一个额外的"{键:值}"对映射到请求一起发送
  • async (默认: true):默认设置下,所有请求均为异步。如果需发送同步请求,请将此设置为 false
  • global (默认: true):请求将触发全局AJAX事件处理程序,设置为 false 将不会触发全局 AJAX 事件。
  • context (默认: window): 这个对象用于设置Ajax相关回调函数的上下文(this指向)。
  • traditional (默认:false):激活传统的方式通过$.param来得到序列化的 data

如果URL中含有 =?或者dataType是“jsonp”,这讲求将会通过注入一个 <script>标签来代替使用 XMLHttpRequest (查看 JSONP)。此时对 contentType, dataType, headers有限制,async 不被支持。

Ajax 回调函数

你可以指定以下的回调函数,给出的执行顺序:

  1. beforeSend(xhr, settings):请求发出前调用,它接收xhr对象和settings作为参数对象。如果它返回 false ,请求将被取消。

  2. success(data, status, xhr):请求成功之后调用。传入返回后的数据,以及包含成功代码的字符串。

  3. error(xhr, errorType, error):请求出错时调用。 (超时,解析错误,或者状态码不在HTTP 2xx)。

  4. complete(xhr, status):请求完成时调用,无论请求失败或成功。

Ajax 事件

global: true时。在Ajax请求生命周期内,以下这些事件将被触发。

  1. ajaxStart (global):如果没有其他Ajax请求当前活跃将会被触发。

  2. ajaxBeforeSend (data: xhr, options):再发送请求前,可以被取消。

  3. ajaxSend (data: xhr, options):像 ajaxBeforeSend,但不能取消。

  4. ajaxSuccess (data: xhr, options, data):当返回成功时。

  5. ajaxError (data: xhr, options, error):当有错误时。

  6. ajaxComplete (data: xhr, options):请求已经完成后,无论请求是成功或者失败。

  7. ajaxStop (global):如果这是最后一个活跃着的Ajax请求,将会被触发。

默认情况下,Ajax事件在document对象上触发。然而,如果请求的 context 是一个dom节点,该事件会在此节点上触发然后再dom中冒泡。唯一的例外是 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
  

执行JSONP跨域获取数据。

此方法相对 $.ajax 没有优势,建议不要使用。

$.ajaxSettings

一个包含Ajax请求的默认设置的对象。大部分的设置在 $.ajax中已经描述。以下设置为全局非常有用:

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

  • timeout (默认: 0):对Ajax请求设置一个非零的值指定一个默认的超时时间,以毫秒为单位。
  • global (默认: true):设置为false。以防止触发Ajax事件。
  • xhr (默认:XMLHttpRequest factory):设置为一个函数,它返回XMLHttpRequest实例(或一个兼容的对象)
  • accepts: 从服务器请求的MIME类型,指定dataType值:
    • 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]
  

执行一个Ajax GET请求。这是一个 $.ajax的简写方式。

$.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]
  

通过 Ajax GET请求获取JSON数据。这是一个 $.ajax 的简写方式。

$.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
  

创建一个序列化的数组或对象,适用于一个URL 地址查询字符串或Ajax请求。如果shallow设置为true。嵌套对象不会被序列化,嵌套数组的值不会使用放括号在他们的key上。

此外,还接受 serializeArray格式的数组,其中每个项都有 “name” 和 “value”属性。

Also 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]"
    

$.post

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

执行Ajax POST请求。这是一个 $.ajax 的简写方式。

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

data 参数可以是一个字符串:

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

load

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

通过GET Ajax载入远程 HTML 文件代码并插入至 DOM 中。另外,一个css选择器可以在url中指定,像这样,可以使用匹配selector选择器的HTML内容来更新集合。

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')
    

当这种方法执行, 它将检索 foo.html 页面的内容,Zepto会获取ID为bar元素的内容,并且插入到ID为 some_element 元素,而其他的被检索到的元素将被废弃。

如果css选择器不存在。将使用完整的返回文本。

请注意,在没有选择器的情况下,任何javascript块都会执行。如果带上选择器,匹配选择器内的script将会被删除。


表单方法

serialize

serialize() ⇒ string
  

在Ajax post请求中将用作提交的表单元素的值编译成 URL-encoded 字符串。

serializeArray

serializeArray() ⇒ array

将用作提交的表单元素的值编译成拥有name和value对象组成的数组。不能使用的表单元素,buttons,未选中的radio buttons/checkboxs 将会被跳过。结果不包含file inputs的数据。

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

submit

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

为 "submit" 事件绑定一个处理函数,或者触发元素上的 "submit" 事件。当参数function没有给出时,触发当前表单“submit”事件,并且执行默认的提交表单行为,除非调用了 preventDefault()

当function参数给出时,在当前元素上它简单得为其在“submit”事件绑定一个处理函数。

 


效果

$.fx

全局动画设置:

  • $.fx.off (在支持css transition 的浏览器中默认为false):设置true来禁止所有animate() transitions。

  • $.fx.speeds:用来设置动画时间的对象。

    • _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
  

对当前Zepto集合对象中元素进行css transition属性平滑过渡。

  • properties: 一个对象,该对象包含了css动画的值,或者css帧动画的名称。
  • duration (默认 400):以毫秒为单位的时间,或者一个字符串。
    • fast (200 ms)
    • slow (600 ms)
    • 任何$.fx.speeds自定义属性
  • easing (默认 linear):指定动画的缓动类型,使用以下一个:
  • complete:动画完成时的回调函数

Zepto 还支持以下 CSS transform 属性:

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

如果duration参数为 0$.fx.off 为 true(在不支持css transitions的浏览器中默认为true),动画将不被执行;替代动画效果的目标位置会即刻生效。类似的,如果指定的动画不是通过动画完成,而且动画的目标位置即可生效。这种情况下没有动画, complete方法也不会被调用。

如果第一个参数是字符串而不是一个对象,它将被当作一个css关键帧动画 CSS keyframe animation的名称。

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

Zepto只使用css过渡效果的动画。jquery的easings不会支持。jquery的相对变化("=+10px") syntax 也不支持。请查看 list of animatable properties。浏览器的支持可能不同,所以一定要测试你所想要支持的浏览器。


触控

Touch events

“touch”模块添加以下事件,可以 onoff

  • tap —元素tap的时候触发。
  • singleTap and doubleTap — 这一对事件可以用来检测元素上的单击和双击。(如果你不需要检测单击、双击,使用 tap 代替)。
  • longTap — 当一个元素被按住超过750ms触发。
  • swipe, swipeLeft, swipeRight, swipeUp, swipeDown — 当元素被划过时触发。(可选择给定的方向)

这些事件也是所有Zepto对象集合上的快捷方法。

<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>
    

更改日志

v1.0 02 Mar 2013diff

Party like it’s one-oh!

Notable changes

  • Zepto is now compatible with Twitter Bootstrap
  • Portable, completely new node.js-based build system
  • Fully automated tests with PhantomJS and Travis CI
  • Removed touch module from default distribution

New features

  • $.fn.filter(function(index){ ... })
  • $.fn.contents()
  • $.fn.wrapInner()
  • $.fn.scrollTop()
  • $.contains()
  • $.fn.has()
  • $.fn.position()
  • $.fn.offsetParent()
  • $.parseJSON()
  • $.camelCase()
  • $.isWindow()
  • $.grep() (interface to Array.filter)
  • Support $(html, attributes) syntax for element creation
  • Emulate mouseenter and mouseleave events
  • Bootstrap compat: support $.fn.offset(coordinates)
  • Bootstrap compat: implement $.fn.detach()
  • Add support for Ajax cache: false option
  • Prevent scrolling when horizontal swipe events are detected
  • cancelTouch for tap events
  • prev and next now support an optional selector argument
  • $.fn.find and $.fn.closest now support Zepto objects as arguments
  • Enable deep copy via $.extend(true, target, source)
  • Enable nested structures for $.fn.wrap() and $.fn.wrapAll()
  • Enable function arguments for $.fn.wrap() and $.fn.wrapInner()
  • Support number, boolean, JSON types in data attributes
  • Support manipulating classnames on SVG elements
  • Enable named durations for animate, e.g. slow.
  • Support timing-function for animate
  • Support event properties passed to $.fn.trigger() or $.Event()
  • Selector module: support child > * queries
  • Add detect support for mobile Chrome browser
  • Add $.os.phone and $.os.tablet (booleans)
  • Detect Firefox mobile, Playbooks and BB10

Fixes

  • Fix passing null selector to on or off
  • Fixed bug where self-closing html tags would act as open tags
  • Fix val for multiple select
  • Fix various touch and gesture bugs.
  • Corrected parameters of load success callback to match jQuery.
  • Fix css with 0 values and falsy values
  • Fix a css performance issues with string values
  • Fix $.ajaxJSONP when invoked directly
  • Fix animate with 0 durations.
  • Fix toggle and fadeToggle for multiple elements.
  • Fix ajax $.fn.load behavior with selector
  • Make attr(name, null) unset attribute
  • Fix animate in Firefox
  • Fix animate for elements just added to DOM
  • Fix an escaping issue with $.param
  • Respect traditional: true option in $.ajax
  • Fix focus & blur event delegation and enable unbind
  • Simple wrapping for any object passed to $()
  • Enable children method for XML documents
  • Don’t eval <script> content when src is present
  • Support processData option for $.ajax()
  • Enable passing contentType: false to $.ajax()
  • Apply focus() and blur() to all elements in collection
  • Change $.fn.map() to return a Zepto collection
  • Selector argument for on(evt, selector, fn) can be false
  • Don’t raise error on $('#')
  • Provide empty object in $.support
  • return false in event handler calls stopPropagation()
  • Fix $.isPlainObject() for window in Opera
  • $.ajax error callback correctly reports abort status
  • Fix hasClass in collections of multiple elements
  • Stop iteration in each() when the callback returns false
  • Add ability to set xhr factory per-request
  • Have get() method accept negative index
  • Support for multiple class names in toggleClass()
  • Fix error callbacks for ajaxJSONP
  • Support optional data argument for various Ajax methods
  • Fix DOM insertion operators for null values
  • Fix dataType being set for $.getJSON

v1.0rc1 09 Apr 2012diff

The semicolon-free edition! That’s right, we removed all trailing semicolons from the source and tests. They were never needed anyway.

New methods:

New module:

  • “selector.js” with experimental support for jQuery CSS pseudo-selectors such as :visible and :first

Improvements in core:

  • added missing methods for Ember.js compatibility
  • improved creating DOM fragments from HTML with $()
  • enable append & family to accept multiple arguments
  • fix $.each context
  • fix calling get without index
  • fix calling val on empty collection
  • using css(property, '') removes the property
  • fix filter, is, and closest when operating on nodes that are detached from the document
  • remove end & andSelf from core to the new “stack.js” plugin
  • exposed important internal Zepto functions through the $.zepto object for extending or overriding Zepto functionality.
  • data method returns undefined when there is no data
  • support camelized names in data method

Apart from improving the basic data method in core, the “data.js” module got improvements as well:

  • better jQuery compatibility
  • ability to store functions
  • new removeData method

Ajax:

  • have correct ajaxComplete argument order for JSONP abort and timeout
  • JSONP requests that hit a 404 will now correctly invoke the error callback
  • add support for dataType: 'jsonp' in $.ajax
  • add support for data in $.ajaxJSONP
  • HTTP 304 status is treated as success instead of an error
  • made load more compatible with jQuery
  • allow Content-Type to be set via request headers
  • respect Content-Type of the response if dataType isn’t set
  • work around Chrome CORS bug when data is empty

Changes in other modules:

  • fix animate for edge cases such as when there is an animation within an animated element, and improve handling of transition CSS properties
  • new “singleTap” event
  • improved “longTap” detection

0.8 03 Nov 2011diff

  • CSS transitions for every browser with animate() method;
  • unified event handling with fn.on() & off();
  • Ajax global events & timeout support;
  • performance boost for selectors.

See full release notes.

0.7 01 Aug 2011diff

  • add $.each, $.map, $.slice;
  • add .serializeArray(), .serialize();
  • add .triggerHandler();
  • add .wrap, .wrapAll, .unwrap, .width/height setters, .append (and friends) improvements;
  • add “longTap” event;
  • .anim() accepts CSS transform properties;
  • return false in event handlers cancels browser event behavior.

0.6 14 May 2011diff

  • add .add, .appendTo, .prependTo, .replaceWith, .empty, .submit;
  • allow function args for .add/.remove/.toggleClass;
  • improvements to events and xhr.

0.5 01 Mar 2011diff

  • add .not, .children, .siblings, $.param;
  • improve .attr & .html;
  • support callback for .anim.

0.4 21 Jan 2011diff

  • JSONP;
  • better .find, .each, .closest;
  • add .eq, .size, .parent, .parents, .removeAttr, .val;
  • support function args in .html, .attr;
  • adjacency methods now take Zepto objects.

0.3 17 Dec 2010diff

  • add .toggleClass, .attr setter, .last, .undelegate, .die;
  • proxied event objects for event delegation;
  • support $ fragments.

0.2 01 Dec 2010diff

  • now compatible with backbone.js;
  • support event unbind;
  • ajax posts with data.

Acknowledgements & Thanks

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-2013 Thomas Fuchs, Freckle Online Time Tracking
Zepto and this documentation is released under the terms of the MIT license.