Zepto Api參考

zepto API參考

簡介
Zepto是一個輕量級的針對現代高級瀏覽器的JavaScript庫, 它與jquery有着相似的api。 若是你會用jquery,那麼你也會用zepto。javascript

設計目的
zepto設計目的是爲移動端提供相似jquery的迷你框架,壓縮後zepto小於10KB.css

下載html

bower install zepto

默認的構建包括如下模塊:
Core, Ajax, Event, Form, Effects, Polyfill, and Detect.java

<script>
    // document.write方式建立script, 移動端或現代瀏覽器用zepto, 舊瀏覽器用jquery
    document.write('<script src=' + ('__proto__' in {} ? 'zepto' : 'jquery') + '.js><\/script>');
</script>

在瀏覽器上(Safari和Chrome)上開發頁面應用或者使用PhoneGap構建基於html的web-view本地應用,使用Zepto是一個不錯的選擇。node

總之,除了ie瀏覽器外,Zepto但願在全部的現代瀏覽器中做爲一種基礎環境來使用。jquery

建立插件android

能夠經過添加方法做爲$.fn的屬性來寫插件:ios

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

核心方法

$(selector, [context])

$(selector, [context]); // => collection
$( zeptoCollection ); // => same collection
$( domNodes ); // => collection
$( htmlString ); // => collection
$( htmlString,  attributes); // => collection v1 .0 +

Zepto(function($) {... });

經過css選擇器 包裝dom節點 建立元素 html片斷 來建立一個Zepto對象。web

Zepto集合是一個相似數組的對象,它具備鏈式方法來操做它指向的dom,除了$對象上的直接方法外(如$.extend),文檔對象中的全部方法都是集合方法。ajax

若是選擇器中存在content參數(css選擇器,dom,或者Zepto集合對象),那麼只在所給的節點背景下進行css選擇器;這個功能有點像使用$(context).find(selector)。

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

將一組字符串變成「駱駝」命名法的新字符串,若是該字符已是「駱駝」命名法,則不變化。

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

$.contains

檢查父節點是否包含給定的dom節點,若是二者相同,則返回 false。

$.contains(parent, node)  //=> boolean

$.each

遍歷數組元素或以key-value值對方式遍歷對象。回調函數返回 false 時中止遍歷

$.each(collection, function(index, item){ ... })  //=> collection
$.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

經過源對象擴展目標對象的屬性,源對象屬性將覆蓋目標對象屬性。
默認狀況下爲,複製爲淺複製。若是第一個參數爲true表示深度複製。

$.extend(target, [source, [source2, ...]]) //=> target
$.extend(true, target, [source, ...]) //=> target

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

獲取一個新數組,新數組只包含回調函數中返回 ture 的數組項。

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

$.inArray

搜索數組中指定值並返回它的索引(若是沒有找到則返回-1)。

// 同 indexOf
$.inArray(element, array, [fromIndex])  //=> number
// [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

// 同 es5 Array.isArray
$.isArray(object)  //=> boolean

$.isFunction

$.isFunction(object)  //=> boolean

$.isPlainObject

測試對象是不是純粹的對象(經過 "{}" 或者 "new Object" 建立的),若是是,則返回true。

$.isPlainObject(object)  //=> boolean

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

$.isWindow

肯定參數是否爲一個窗口(window對象),若是是則返回true。
這在處理iframe時很是有用,由於每一個iframe都有它們本身的window對象,使用常規方法obj==window校驗這些objects的時候會失敗。

$.isWindow(object)  //=> boolean

$.map

經過遍歷集合中的元素,經過函數返回一個新的數組,null and undefined 將被過濾掉

// 同 map  迭代函數的參數1爲 value, 參數2爲key, 這點上與$.each有區別
$.map(collection, function(item, index){ ... })  //=> collection
$.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

相似本地JSON.parse 方法,接受一個標準格式的 JSON 字符串,並返回解析後的 JavaScript 對象。

$.parseJSON(string)  //=> object

$.trim

刪除字符串開始和末尾的空白符。相似String.prototype.trim()。

$.trim(string)  //=> string

$.type

獲取JavaScript 對象的類型。可能的類型有: null undefined boolean number string function array date regexp object error。
對於其它對象,它只是簡單報告爲「object」,若是你想知道一個對象是不是一個javascript普通對象,使用isPlainObject。

// jq原來也有 $.type方法..
$.type(object)  //=> string

zepto對象的方法

add

添加元素到匹配的元素集合。若是content參數存在,只在content中進行查找,不然在document中查找。

$ele.add(selector, [context])  //=> self


<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

爲每一個匹配的元素添加指定的class類名。多個class類名經過空格分隔。

$ele.addClass(name)  //=> self
$ele.addClass(function(index, oldClassName){ ... })  //=> self

after

在每一個匹配的元素後插入內容。內容能夠爲html字符串,dom節點,或者節點組成的數組。

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

append

在每一個匹配的元素末尾插入內容。內容能夠爲html字符串,dom節點,或者節點組成的數組。

$ele.append(content)  //=> self
$('ul').append('<li>new list item</li>')

appendTo

將匹配的元素插入到目標元素的末尾(裏面的後面)。這個有點像 append,可是插入的目標與其相反。

$ele.appendTo(target)  //=> self
$('<li>new list item</li>').appendTo('ul')

attr

讀取或設置dom的屬性。若是沒有給定value參數,則讀取Zepto對象第集合一個元素的屬性值。當給定了value參數。則設置Zepto對象集合中全部元素全部元素的屬性值。當value參數爲null,那麼這個屬性將被移除(相似removeAttr),多個屬性能以經過對象值對的方式進行設置。

$ele.attr(name) //=> string
$ele.attr(name, value) //=> self
$ele.attr(name, function(index, oldValue) {... }) //=> self
$ele.attr({ name: value, name2: value2, ... }) //=> self

要讀取dom的屬性如 checked和selected, 使用 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

在匹配每一個元素的前面(外面)插入內容。內容能夠爲html字符串,dom節點,或者節點組成的數組。

$ele.before(content)  //=> self
$('table').before('<p>See the following table:</p>')

children

得到每一個匹配元素集合元素的直接子元素,若是selector存在,只返回符合css選擇器的元素。

$ele.children([selector])  //=> collection
$('ol').children('*:nth-child(2n)');  //=> every other list item from every ordered list

clone

經過深度克隆來複制集合中的全部元素。
此方法不會有數據和事件處理程序複製到新的元素。這點和jquery中利用一個參數來肯定是否複製數據和事件處理不相同。

$ele.clone()  //=> collection

closest

從元素自己開始,逐級向上級元素匹配,並返回最早匹配selector的祖先元素。若是context節點參數存在。那麼直考慮該節點的後代。這個方法與 parents(selector)有點相像,但他只返回最早匹配的祖先元素。

$ele.closest(selector, [context]) //=> collection
$ele.closest(collection) //=> collection
$ele.closest(element) //=> collection

若是參數是一個Zepto對象集合或者一個元素,結果必須匹配給定的元素而不是選擇器。

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

concat

添加元素到一個Zepto對象集合造成一個新數組。若是參數是一個數組,那麼這個數組中的元素將會合併到Zepto對象集合中。
這是一個Zepto提供的方法,不是jquey的API 。

// 相似 $ele.add(selector, [context])
$ele.concat(nodes, [node2, ...])  //=> self

contents

得到每一個匹配元素集合元素的子元素,包括文字和註釋節點。.contents()和.children()方法相似,只不過前者包括文本節點以及註釋等,後者只包含子元素。

$ele.contents()  //=> collection

css

讀取或設置dom元素的css屬性。當value參數不存在的時候,返回Zepto對象集合中第一個元素的css屬性。當value參數存在時,設置Zepto對象集合中每個元素的對應css屬性。多條css屬性能夠利用對象值對的方式進行設置。

$ele.css(property) //=> value
$ele.css(property, value) //=> self
$ele.css({ property: value, property2: value2, ... }) //=> self

當value爲空(空字符串,null 或 undefined),那個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

讀取或寫入dom的 data-* 屬性。行爲有點像 attr ,可是屬性名稱前面加上 data-。

$ele.data(name)  //=> value
$ele.data(name, value)  //=> self

當讀取屬性值時,會有下列轉換:v1.0+

  1. 「true」, 「false」, and 「null」 被轉換爲相應的類型; 轉換邏輯值和null
  2. 數字值轉換爲實際的數字類型;
  3. JSON值將會被解析,若是它是有效的JSON;
  4. 其它的一切做爲字符串返回。

Zepto 基本實現data()只能存儲字符串。若是你要存儲任意對象,請引入可選的「data」模塊到你構建的Zepto中。

each

遍歷一個Zepto集合對象,爲每個匹配元素執行一個函數。this關鍵字指向當前item(做爲函數的第二個參數傳遞)。若是函數返回 false,遍歷結束。

$ele.each(function(index, item){ ... })  //=> self

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

$ele.empty() //=> self

eq

從當前Zepto對象集合中獲取給定索引號的元素。

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

filter

過濾Zepto集合對象,返回的Zepto集合對象裏面的項知足參數中的css選擇器。若是參數爲一個函數,函數返回有實際值得時候,元素纔會被返回。在函數中, this 關鍵字指向當前的元素。

$ele.filter(selector)  //=> collection
$ele.filter(function(index){ ... })  //=> collection

find

得到當前Zepto集合對象內查找符合css選擇器的每一個元素的後代。
若是參數爲Zepto集合對象或者元素,過濾它們,只有當它們在當前Zepto集合對象中時,才被返回。

$ele.find(selector) //=> collection
$ele.find(collection) //=> collection
$ele.find(element) //=> collection

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

first

$ele.first()  //=> collection
// 獲取當前Zepto對象集合中的第一個元素。
$('form').first()

forEach

遍歷當前Zepto集合對象的買個元素,有點相似 each,可是遍歷函數的參數不同,當函數返回 false 的時候,遍歷不會中止。

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

這是一個Zepto提供的方法,不是jquery的API。

get

get()  //=> array
get(index)  //=> DOM node

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

從當前Zepto對象集合中獲取全部元素或單個元素。當index參數不存在的時候,以普通數組的方式返回全部的元素。當指定index時,只返回該置的元素。這點與與eq不一樣,該方法返回的不是Zepto集合對象。

has

$ele.has(selector)  //=> collection
$ele.has(node)  //=> collection

判斷當前Zepto對象集合的子元素是否有符合選擇器的元素,或者是否包含指定的dom節點,若是有,則返回新的Zepto集合對象,該對象過濾掉不含有選擇器匹配元素或者不含有指定dom節點的對象。

// __返回值非boolean值,而是匹配的dom__
$('ol > li').has('a[href]'); //=> get only LI elements that contain links

hasClass

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

$ele.height() //=> number
$ele.height(value) //=> self
$ele.height(function(index, oldHeight){ ... }) //=> self

獲取Zepto對象集合中第一個元素的高度;或者設置Zepto對象集合中全部元素的高度。

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

hide

$ele.hide()  //=> self

經過設置css的屬性 display: none 來將Zepto對象集合中的元素隱藏。

html

$ele.html()  //=> string
$ele.html(content)  //=> self
$ele.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

$ele.index([element])  //=> number
$('li:nth-child(2)').index() //=> 1

獲取一個元素的位置。當elemen參數沒有給出時,返回當前元素在兄弟節點中的位置。當element參數給出時,返回它在當前Zepto對象集合中的位置。若是沒有該元素,則返回-1。

indexOf

$ele.indexOf(element, [fromIndex])  //=> number

在當前Zepto中獲取一個元素的位置。若是formindex參數給出,從該位置日後查找,返回基於0的位置,若是沒找到,則返回-1。index 方法是基於這個方法實現的。

這是一個Zepto的方法,不是jquer的api。

insertAfter

$ele.insertAfter(target)  //=> self
$('<p>Emphasis mine.</p>').insertAfter('blockquote')

插入Zepto對象集合中的元素到指定的每一個元素後面的dom中。這個有點像 after,可是使用方式相反。

insertBefore

$ele.insertBefore(target)  //=> self
$('<p>See the following table:</p>').insertBefore('table')

插入Zepto對象集合中的元素到指定的每一個元素前面的dom中。這個有點像 before,可是使用方式相反。

is

$ele.is(selector) //=> boolean

判斷當前Zepto元素集合中的第一個元素是否符css選擇器。對於基礎支持jquery的非標準選擇器相似::visible包含在可選的「selector」模塊中。

jQuery CSS extensions 不被支持。 選擇「selector」模塊僅僅能支持有限幾個最經常使用的方式。

last

$ele.last()  //=> collection
$('li').last()

獲取Zepto集合對象中最後一個元素。

map

// $.map(function(item, index))
$ele.map(function(index, item){ ... })  //=> collection 

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

遍歷Zepto對象集合中的全部元素。經過遍歷函數返回值造成一個新的集合對象。在遍歷函數中this關鍵之指向當前循環的item(遍歷函數中的第二個參數)。遍歷中返回 null和undefined,遍歷將被打斷

next

$ele.next()  //=> collection
$ele.next(selector)  //=> collection
$('dl dt').next();  //=> the DD element

獲取Zepto對象集合中每個元素的下一個兄弟節點(能夠選擇性的帶上過濾選擇器)。

not

$ele.not(selector)  //=> collection
$ele.not(collection)  //=> collection
$ele.not(function(index){ ... })  //=> collection

過濾當前Zepto對象集合,獲取一個新的Zepto對象集合,它裏面的元素不能匹配css選擇器。若是另外一個參數爲Zepto集合對象,那麼返回的新Zepto對象中的元素都不包含在該參數對象中。若是參數是一個函數。僅僅包含函數執行爲false值得時候的元素,函數的 this 關鍵字指向當前循環元素。

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

offset

$ele.offset()  //=> object
$ele.offset(coordinates)  //=> self
$ele.offset(function(index, oldOffset){ ... })  //=> self

得到當前元素相對於document的位置。返回一個對象含有: top, left, width和height
當給定一個對象屬性left和top使用這些值來相對於document對每個元素進行定位。

offsetParent

$ele.offsetParent()  //=> collection

找到第一個定位過的祖先元素,在ccs中意味着它的position 值爲「relative」, 「absolute」 or 「fixed」

parent

$ele.parent([selector])  //=> collection

獲取Zepto對象集合中每一個元素的直接父元素。若是css選擇器參數給出。過濾出符合條件的元素。

parents

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

獲取Zepto對象集合每一個元素全部的祖先元素。若是css選擇器參數給出,過濾出符合條件的元素。
若是想獲取直接父級元素,使用 parent。若是隻想獲取到第一個符合css選擇器的元素,使用closest。

pluck

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

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

獲取Zepto對象集合中每個元素的屬性值。返回值爲 null或undefined值得過濾掉。

這是一個Zepto的方法,不是jquery的api

position

$ele.position()  //=> object
var pos = element.position();

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

獲取Zepto對象集合中第一個元素的位置。相對於 offsetParent。當絕對定位的一個素靠近另外一個元素的時候,這個方法是有用的。
返回一個的對象有這些屬性:top, left。

prepend

$ele.prepend(content)  //=> self
$('ul').prepend('<li>first list item</li>');

將參數內容插入到每一個匹配元素的前面(元素內部)。插入d的元素能夠試html字符串片斷,一個dom節點,或者一個節點的數組。

prependTo

$ele.prependTo(target)  //=> self
$('<li>first list item</li>').prependTo('ul')

將全部元素插入到目標前面(元素內)。這有點像prepend,可是是相反的方式。

prev

$ele.prev()  //=> collection
$ele.prev(selector)  //=> collection

獲取Zepto對象集合中每個元素的前一個兄弟節點,經過選擇器來進行過濾。

prop

$ele.prop(name)  //=> value
$ele.prop(name, value)  //=> self
$ele.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

$ele.push(element, [element2, ...])  //=> self

添加元素到當前Zepto對象的最後。

這是一個zepto的方法,不是jquery的api

ready

$(document).ready(function($){ ... })  //=> self

添加一個事件偵聽器,當頁面dom加載完畢 「DOMContentLoaded」 事件觸發時觸發。建議使用 $()來代替這種用法。

reduce

$ele.reduce(function(memo, item, index, array){ ... }, [initial])  //=> value

與 Array.reduce有相同的用法,遍歷當前Zepto對象集合。memo是函數上次的返回值。迭代進行遍歷。

這是一個zepto的方法,不是jquery的api

remove

$ele.remove()  //=> self

移出當前Zepto對象中的元素。有效的從dom中移除。

removeAttr

$ele.removeAttr(name)  //=> self

移動當前Zepto對象集合中全部元素的指定屬性。

removeClass

$ele.removeClass([name])  //=> self
$ele.removeClass(function(index, oldClassName){ ... })  //=> self
$("#check1").removeClass("taiyang yueliang")

移動當前Zepto對象集合中全部元素的指定class。若是name參數未給出。將移出全部的class。多個class參數名稱能夠利用空格分隔。下例移除了兩個class。

replaceWith

$ele.replaceWith(content)  //=> self

用提供的內容替換全部匹配的元素。(包含元素自己)。content參數能夠爲 before中描述的類型。

scrollTop

$ele.scrollTop()  //=> number

獲取頁面上的滾動元素或者整個窗口已經滾動的像素值。

show

$ele.show()  //=> self

恢復Zepto對象集合中每一個元素默認的「display」值。若是你用 hide將元素隱藏,用該屬性能夠將其顯示。至關於幹掉了display:none。

siblings

$ele.siblings([selector])  //=> collection

獲取Zepto集合對象全部兄弟節點。若是css選擇器參數給出。過濾出符合選擇器的元素。

size

$ele.size()  //=> number

獲取Zepto對象集合中元素的數量。

slice

$ele.slice(start, [end])  //=> array

array中提取的方法。從start開始,若是end 指出。提取不包含end位置的元素。

text

$ele.text()  //=> string
$ele.text(content)  //=> self

獲取或者設置全部Zepto對象的文本內容。當content參數未給出。返回當前Zepto對象集合中第一個元素的文本內容(包含子節點中的文本內容)。當content參數給出,使用它替換Zepto對象集合中全部元素的文本內容。它有待點似 html,與它不一樣的是它不能用來獲取或設置 HTML。

toggle

$ele.toggle([setting])  //=> self

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

顯示或隱藏匹配元素。若是 setting爲true,至關於show 法。若是setting爲false。至關於 hide方法。

toggleClass

$ele.toggleClass(names, [setting])  //=> self
$ele.toggleClass(function(index, oldClassNames){ ... }, [setting])  //=> self

在匹配的元素集合中的每一個元素上添加或刪除一個或多個樣式類。若是class的名稱存在則刪除它,若是不存在,就添加它。若是 setting的值爲真,這個功能相似於 addClass,若是爲假,這個功能相似與 removeClass。

unwrap

$ele.unwrap()  //=> self

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

將匹配元素的父級元素刪除,保留自身(和兄弟元素,若是存在)在原來的位置。

val

$ele.val()  //=> string
$ele.val(value)  //=> self
$ele.val(function(index, oldValue){ ... })  //=> self

獲取或設置匹配元素的值。當value參數不存在。返回第一個元素的值。若是是<select multiple>標籤,則返回一個數組。

width

$ele.width()  //=> number
$ele.width(value)  //=> self
$ele.width(function(index, oldWidth){ ... })  //=> self

獲取Zepto對象集合中第一個元素的寬;或者設置Zepto對象集合全部元素的寬。

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

wrap

$ele.wrap(structure)  //=> self
$ele.wrap(function(index){ ... })  //=> self

在每一個匹配的元素外層包上一個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

$ele.wrapAll(structure)  //=> self

在全部匹配元素外面包一層HTML結構。

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

wrapInner

$ele.wrapInner(structure)  //=> self
$ele.wrapInner(function(index){ ... })  //=> self

// 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>'); //<ol><li><p><em>old text</em></p></li></ol>

在匹配元素裏的內容外包一層結構。

檢測方法

該檢測方法能夠在不一樣的環境中微調你的站點或者應用程序,並幫助你識別手機和平板;以及不一樣的瀏覽器和操做系統。

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

事件處理

$.Event

$.Event(type, [properties]) //=> event
建立並初始化一個指定的dom事件。若是properties參數給出,使用它來擴展出新的事件對象。默認狀況下,事件被設置爲冒泡方式;這個能夠經過設置bubbles爲false來關閉。

初始化的事件可使用 trigger來觸發。 建立event對象的場景並很少

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

$.proxy

$.proxy(fn, context)  //=> function
$.proxy(context, property)  //=> function

var obj = {name: 'Zepto'};
var 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: "world",
    test: function() {
        alert(this.name);
        $("#test").unbind("click", obj.test);
    }
};

$("#test").click(jQuery.proxy(obj, "test"));

接受一個函數,而後返回一個新函數,而且這個新函數始終保持了特定的上下文語境,新函數中this指向context參數。另一種形式,原始的function是context對像的方法。

bind 用 on 替代

$ele.bind(type, function(e){ ... })  //=> self
$ele.bind({ type: handler, type2: handler2, ... })  //=> self

爲一個元素綁定一個處理事件。

delegate 用on代替

$ele.delegate(selector, type, function(e){ ... }) //=> self
$ele.delegate(selector, { type: handler, type2: handler2, ... }) //=> self

基於一組特定的根元素爲全部選擇器匹配的元素附加一個處理事件,匹配的元素可能如今或未來才建立。

die

$ele.die(type, function(e){ ... })  //=> self
$ele.die({ type: handler, type2: handler2, ... })  //=> self

刪除經過 live 添加的事件。

live

$ele.live(type, function(e){ ... })  //=> self
$ele.live({ type: handler, type2: handler2, ... })  //=> self

相似delegate,添加一個個事件處理器到符合目前選擇器的全部元素匹配,匹配的元素可能如今或未來才建立。

off

$ele.off(type, [selector], function(e){ ... })  //=> self off委託事件的某個回調
$ele.off({ type: handler, type2: handler2, ... }, [selector])  //=> self  off多個事件回調
$ele.off(type, [selector])  //=> self  off委託的事件
$ele.off()  //=> self off全部事件

移除經過 on 註冊的事件(用bind或者用on註冊的事件)。若是沒有參數,將移出當前元素上全部的註冊事件。

//若是selector存在,則至關於delegate。
$ele.off(type, [selector], function(e){ ... }) //=> self
$("ul").on("click","li",function(){alert("yaotaiyang")});
//至關於將li的事件代理到ul上。後續添加的li也能擁有以上方法。該事件能夠經過undelegate來移除。
$("ul").undelegate();  //也可用:$("ul").off();

on 集成bind和delegate方法。

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

one

$ele.one(type, function(e){ ... }) //=> self
$ele.one({ type: handler, type2: handler2, ... }) //=> self

添加一個處理事件到元素。處理函數在每一個元素上最多執行一次。

trigger

$ele.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']);

triggerHandler

$ele.triggerHandler(event, [data])  //=> self
$input.triggerHandler('focus');

像 trigger,它只觸發事件回調,沒有瀏覽器的默認行爲。

unbind

$ele.unbind(type, function(e){ ... })  //=> self
$ele.unbind({ type: handler, type2: handler2, ... })  //=> self

移除經過 bind 註冊的事件。

undelegate

$ele.undelegate(selector, type, function(e){ ... })  //=> self
$ele.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 回調函數

你能夠指定如下的回調函數,給出的執行順序:

  • beforeSend(xhr, settings):請求發出前調用,它接收xhr對象和settings做爲參數對象。若是它返回false ,請求將被取消。

  • success(data, status, xhr):請求成功以後調用。傳入返回後的數據,以及包含成功代碼的字符串。

  • error(xhr, errorType, error):請求出錯時調用。 (超時,解析錯誤,或者狀態碼不在HTTP 2xx)。

  • complete(xhr, status):請求完成時調用,不管請求失敗或成功。

Ajax 事件

當global: true時。在Ajax請求生命週期內,如下這些事件將被觸發。

  • ajaxStart (global):若是沒有其餘Ajax請求當前活躍將會被觸發。

  • ajaxBeforeSend (data: xhr, options):再發送請求前,能夠被取消。

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

  • ajaxSuccess (data: xhr, options, data):當返回成功時。

  • ajaxError (data: xhr, options, error):當有錯誤時。

  • ajaxComplete (data: xhr, options):請求已經完成後,不管請求是成功或者失敗。

  • 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: {name: 'Zepto.js'},
    dataType: 'json',  // type of data we are expecting in return:
    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',
    data: JSON.stringify({name: 'Zepto.js'}),
    contentType: 'application/json'
});

$.ajaxSettings

一個包含Ajax請求的默認設置的對象。大部分的設置在 $.ajax中已經描述。如下設置爲全局很是有用:

  • 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

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

執行一個Ajax GET請求。這是一個 $.ajax的簡寫方式。

$.getJSON

$.getJSON(url, function(data, status, xhr){ ... })  //=> XMLHttpRequest
$.getJSON(url, [data], function(data, status, xhr){ ... })  //=> XMLHttpRequest

經過 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查詢字符串;若是shallow設置爲true。嵌套對象不會被序列化,嵌套數組的值不會使用放括號在他們的key上。
此外,還接受 serializeArray格式的數組,其中每一個項都有 「name」 和 「value」屬性。

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

$ele.load(url, function(data, status, xhr){ ... })  //=> self

經過GET Ajax載入遠程 HTML 文件代碼並插入至 DOM 中。另外,一個css選擇器能夠在url中指定,像這樣,可使用匹配selector選擇器的HTML內容來更新集合。

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

當這種方法執行, 它將檢索 foo.html 頁面的內容,Zepto會獲取ID爲bar元素的內容,而且插入到ID爲 some_element 元素,而其餘的被檢索到的元素將被廢棄。
若是css選擇器不存在。將使用完整的返回文本。
請注意,在沒有選擇器的狀況下,任何javascript塊都會執行。若是帶上選擇器,匹配選擇器內的script將會被刪除。

表單方法

serialize

$form.serialize()  //=> string

在Ajax post請求中將用做提交的表單元素的值編譯成 URL-encoded 字符串。

serializeArray

$form.serializeArray()  //=> array

將用做提交的表單元素的值編譯成擁有name和value對象組成的數組。不能使用的表單元素,buttons,未選中的radio buttons/checkboxs 將會被跳過。結果不包含file inputs的數據。

//表單序列化爲對象數組
$('form').serializeArray();  //=> [{ name: 'size', value: 'micro' }, { name: 'name', value: 'Zepto' }]

submit

$form.submit()  //=> self
$form.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)

animate

$ele.animate(properties, [duration, [easing, [function(){ ... }]]])  //=> self
$ele.animate(properties, { duration: msec, easing: type, complete: fn })  //=> self
$ele.animate(animationName, { ... })  //=> self

對當前Zepto集合對象中元素進行css transition屬性平滑過渡。

  • properties: 一個對象,該對象包含了css動畫的值,或者css幀動畫的名稱。
  • duration (默認 400):以毫秒爲單位的時間,或者一個字符串 ( fast, slow)。
    fast (200 ms), slow (600 ms), 任何$.fx.speeds自定義屬性
  • easing (默認 linear):指定動畫的緩動類型
    使用如下一個: ease/ linear / ease-in / ease-out /ease-in-out /cubic-bezier(...)
  • 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)
    若是第一個參數是字符串而不是一個對象,它將被看成一個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的相對變化("=+10px") syntax 也不支持。

觸控

Touch events

  • tap —元素tap的時候觸發。
  • singleTap and doubleTap — 這一對事件能夠用來檢測元素上的單擊和雙擊。(若是你不須要檢測單擊、雙擊,使用 tap 代替)。
  • longTap — 當一個元素被按住超過750ms觸發。
  • swipe, swipeLeft, swipeRight, swipeUp, swipeDown — 當元素被劃過期觸發。(可選擇給定的方向)
相關文章
相關標籤/搜索