zepto.js自己去官網下載哈。 DOM操作 $(document).ready(function(){ var $cr = $("<div class='cr'>插入的div</div>"); // 插入操作 $("#a").append($cr); $cr.appendTo($("#a")); ...
zepto.js自己去官網下載哈。
DOM操作
$(document).ready(function(){ var $cr = $("<div class='cr'>插入的div</div>"); // 插入操作 $("#a").append($cr); $cr.appendTo($("#a")); $("#a").prepend($cr); $cr.prependTo($("#a")); $("#a").after($cr); $cr.insertAfter($("#a")); $("#a").before($cr); $cr.insertBefore($("#a")); // 刪除 remove\empty $("ul li").remove(); $("ul li").empty(); // 複製節點 $("ul li").click(function(){ $(this).clone().appendTo("ul"); }); // 替換節點 replaceWith $("p").replaceWith("<span>是的,哈哈</span>"); // 包裹節點 wrap wrapAll $("p").wrap("<div></div>"); $("p").wrapAll("<div></div>"); });
屬性與樣式操作
$(document).ready(function(){ // 屬性操作 attr("title") attr("name","att") attr({"name":"att" , "class":"test"}) removeAttr("title name") console.log($("div").attr("title")); $("div").attr("name","att"); $("div").attr({"name":"att" , "class":"test"}) $("div").removeAttr("title name"); // 添加樣式操作 addClass $("div").addClass("red").addClass("fs"); $("div").addClass("red fs"); // 刪除class類 removeClass $("div").removeClass(); // 切換樣式 toggle toggleClass $("button").click(function(){ $("div").toggle(); // show和hide的切換 $("div").toggleClass("red"); // addClass("red")和removeClass("red"); }); // 判斷是否含有某個樣式 hasClass console.log($("div").hasClass("red fs")) });
遍歷節點
$(document).ready(function(){ // next是取得緊鄰的後面的同輩元素 console.log($("#one h3").next()); // prev獲取緊鄰的前面的同輩元素 console.log($("#one a").prev()); // siblings獲取前後的所有同輩元素 console.log($("#one p").siblings()); // parent與parents直系親屬 console.log($("b").parent()); console.log($("b").parents()); });
CSS-DOM操作
$(document).ready(function(){ $(".one").css("color", "red").css("fontSize", "36px"); $(".one").css({ color:"red", fontSize:"36px" }); $(".one").width(500); $(".one").height(500); });
ready與onload的區別
// html文件 、 css文件 、 js文件 、 圖片文件等 $(document).ready(function(){ // DOM載入完畢,圖片並未完全載入,調用時機比較快 }); window.onload = function(){ // 全部文件載入完畢,調用時機比較久 }
事件開頭簡寫
$(document).ready(function(){ }) $(function(){ }) $().ready(function(){ })
事件綁定
$(".one").bind("click", function(e){ console.log("one被點擊了!!!") }) $(".one").click(function(e){ console.log("我是簡寫方式"); }) $(".one").on("click", function(e){ console.log("我是on事件"); }); --------------------------------- // on $("ul").on('click', 'li', function(e){ }) // off $("li").off();
zepto不支持事件捕獲
事件其他用法
// 自定義事件 $("div").bind("muke", function(){ console.log("觸發自定義事件"); }); $("div").trigger("muke"); // 命名空間 $("div").bind("click", function(){ console.log("我是普通的click事件"); }) $("div").bind("click.muke", function(){ console.log("我是click.muke的事件"); }) $("div").unbind(".muke"); // 綁定多個事件 $("div").bind("click", function(){ console.log(111) }).bind("touchstart", function(){ console.log(222) })
動畫
$('button').on('click' , function(){ $('div').toggle('slow'); //切換元素的顯示與隱藏 $('div').hide(3000); $('div').show('slow'); $('div').fadeIn('slow'); $('div').fadeOut('slow'); $('div, button').fadeToggle('slow'); $("div").fadeTo(3000 , 1) })
animate() 動畫函數
$("div").animate({left:"300px", height:"300px"}, 3000, function(){ alert("動畫執行完畢"); })
Ajax
function Ajax(){ var xmlHttpReq = null; if(window.ActiveXObject){ // 相容IE5、IE6 xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); }else{ xmlHttpReq = new XMLHttpRequest(); } xmlHttpReq.open("GET", "test.php", true); xmlHttpReq.onreadystatechange = RequestCallBack; function RequestCallBack(){ if(xmlHttpReq.readyState == 4){ if(xmlHttpReq.status == 200){ console.log("獲取數據:"+xmlHttpReq.responseText); } } } xmlHttpReq.send(null); }
ajax請求
// get $.get('urlxxx',function(response){ $(document.body).append(response) }); // post $.post('urlxxx', { sample: 'payload' }, function(response){ }); // ajax $.ajax({ type: 'GET', url: 'urlxxx', data: { name: 'Zepto.js' }, dataType: 'json', success: function(data){ this.append(data.project.html) }, error: function(xhr, type){ alert('Ajax error!') } })
touch模塊
先引入touch.js
<script type="text/javascript" src="../../lib/touch.js"></script>
touch.js
;(function($){ var touch = {}, touchTimeout, tapTimeout, swipeTimeout, longTapTimeout, longTapDelay = 750, gesture function swipeDirection(x1, x2, y1, y2) { return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down') } function longTap() { longTapTimeout = null if (touch.last) { touch.el.trigger('longTap') touch = {} } } function cancelLongTap() { if (longTapTimeout) clearTimeout(longTapTimeout) longTapTimeout = null } function cancelAll() { if (touchTimeout) clearTimeout(touchTimeout) if (tapTimeout) clearTimeout(tapTimeout) if (swipeTimeout) clearTimeout(swipeTimeout) if (longTapTimeout) clearTimeout(longTapTimeout) touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null touch = {} } function isPrimaryTouch(event){ return (event.pointerType == 'touch' || event.pointerType == event.MSPOINTER_TYPE_TOUCH) && event.isPrimary } function isPointerEventType(e, type){ return (e.type == 'pointer'+type || e.type.toLowerCase() == 'mspointer'+type) } $(document).ready(function(){ var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType if ('MSGesture' in window) { gesture = new MSGesture() gesture.target = document.body } $(document) .bind('MSGestureEnd', function(e){ var swipeDirectionFromVelocity = e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null if (swipeDirectionFromVelocity) { touch.el.trigger('swipe') touch.el.trigger('swipe'+ swipeDirectionFromVelocity) } }) .on('touchstart MSPointerDown pointerdown', function(e){ if((_isPointerType = isPointerEventType(e, 'down')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0] if (e.touches && e.touches.length === 1 && touch.x2) { // Clear out touch movement data if we have it sticking around // This can occur if touchcancel doesn't fire due to preventDefault, etc. touch.x2 = undefined touch.y2 = undefined } now = Date.now() delta = now - (touch.last || now) touch.el = $('tagName' in firstTouch.target ? firstTouch.target : firstTouch.target.parentNode) touchTimeout && clearTimeout(touchTimeout) touch.x1 = firstTouch.pageX touch.y1 = firstTouch.pageY if (delta > 0 && delta <= 250) touch.isDoubleTap = true touch.last = now longTapTimeout = setTimeout(longTap, longTapDelay) // adds the current touch contact for IE gesture recognition if (gesture && _isPointerType) gesture.addPointer(e.pointerId) }) .on('touchmove MSPointerMove pointermove', function(e){ if((_isPointerType = isPointerEventType(e, 'move')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0] cancelLongTap() touch.x2 = firstTouch.pageX touch.y2 = firstTouch.pageY deltaX += Math.abs(touch.x1 - touch.x2) deltaY += Math.abs(touch.y1 - touch.y2) }) .on('touchend MSPointerUp pointerup', function(e){ if((_isPointerType = isPointerEventType(e, 'up')) && !isPrimaryTouch(e)) return cancelLongTap() // swipe if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) || (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)) swipeTimeout = setTimeout(function() { if (touch.el){ touch.el.trigger('swipe') touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2))) } touch = {} }, 0) // normal tap else if ('last' in touch) // don't fire tap when delta position changed by more than 30 pixels, // for instance when moving to a point and back to origin if (deltaX < 30 && deltaY < 30) { // delay by one tick so we can cancel the 'tap' event if 'scroll' fires // ('tap' fires before 'scroll') tapTimeout = setTimeout(function() { // trigger universal 'tap' with the option to cancelTouch() // (cancelTouch cancels processing of single vs double taps for faster 'tap' response) var event = $.Event('tap') event.cancelTouch = cancelAll // [by paper] fix -> "TypeError: 'undefined' is not an object (evaluating 'touch.el.trigger'), when double tap if (touch.el) touch.el.trigger(event) // trigger double tap immediately if (touch.isDoubleTap) { if (touch.el) touch.el.trigger('doubleTap') touch = {} } // trigger single tap after 250ms of inactivity else { touchTimeout = setTimeout(function(){ touchTimeout = null if (touch.el) touch.el.trigger('singleTap') touch = {} }, 250) } }, 0) } else { touch = {} } deltaX = deltaY = 0 }) // when the browser window loses focus, // for example when a modal dialog is shown, // cancel all ongoing events .on('touchcancel MSPointerCancel pointercancel', cancelAll) // scrolling the window indicates intention of the user // to scroll, not tap or swipe, so cancel all ongoing events $(window).on('scroll', cancelAll) }) ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){ $.fn[eventName] = function(callback){ return this.on(eventName, callback) } }) })(Zepto)
使用時:
<script> $(document).ready(function(){ $('#touch_test').bind('touchmove', function(e) { e.preventDefault() }) listen_to('#touch_test') function listen_to(el) { $(el).tap(function(){ console.log(' | tap!') }) .doubleTap(function(){ console.log(' | double tap!') }) .swipe(function(){ console.log(' | swipe!') }) .swipeLeft(function(){ console.log(' | swipe left!') }) .swipeRight(function(){ console.log(' | swipe right!') }) .swipeUp(function(){ console.log(' | swipe up!') }) .swipeDown(function(){ console.log(' | swipe down!') }) .longTap(function(){ console.log(' | long tap!') }) .singleTap(function(){ console.log(' | single tap!') }) } }); </script>
插件的寫法
先編寫自定義插件js文件
zepto.color.js
;(function($){ //一個插件的寫法 $.fn.color = function(option){ var options = $.extend({ col: "blue", fz : "20px" }, option); this.css("color", options.col); this.css("fontSize", options.fz); return this; } })(Zepto); //多組插件寫法 /* ;(function($){ $.extend($.fn, { color: function(option){ var options = $.extend({ col: "blue", fz : "20px" }, option); this.css("color", options.col); this.css("fontSize", options.fz); return this; }, background: function(option){ var options = $.extend({ bg: "blue" }, option); this.css("background", options.bg); return this; } }) })(Zepto); */
使用時:
<script type="text/javascript" src="../../lib/zepto.color.js"></script> <script type="text/javascript"> $("div").color({ col : "red" }).addClass("helloworld"); </script>