WebApp开发-Zepto

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").after($cr);
    $cr.insertAfter($("#a").before($cr);
    $cr.insertBefore($("#a"));

     删除 remove\empty
    $("ul li").remove();
    $("ul li").empty();

     复制节点
    $("ul li").click((){
        $(this).clone().appendTo("ul");
    });

     替换节点  replaceWith
    $("p").replaceWith("<span>是的,哈哈</span>");

     包裹节点   wrap  wrapAll
    $("p").wrap("<div></div>");
    $("p").wrapAll("<div></div>");
});

属性与样式操作

$(document).ready( 属性操作  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((){
        $("div").toggle();    show和hide的切换
        $("div").toggleClass("red");    addClass("red")和removeClass("red");
    });    

     判断是否含有某个样式  hasClass
    console.log($("div").hasClass("red fs"))
});

遍历节点

$(document).ready( 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((){
    $(".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((){
         DOM加载完毕,图片并未完全加载,调用时机比较快
    });
    window.onload =  全部文件加载完毕,调用时机比较久
    }

事件开头简写

    $(document).ready((){

    })
    $((){

    })
    $().ready((){

    })

事件绑定

    $(".one").bind("click",(e){
        console.log("one被点击了!!!")
    })

    $(".one").click((e){
        console.log("我是简写方式");
    })

    $(".one").on("click",1)">(e){
        console.log("我是on事件");
    });
---------------------------------
     on 
    $("ul").on('click','li',1)">(e){

    })
     off 
    $("li").off();


zepto不支持事件捕获

事件其他用法

     自定义事件
    $("div").bind("muke",1)">(){
        console.log("触发自定义事件");
    });
    $("div").trigger("muke" 命名空间
    $("div").bind("click",1)">(){
        console.log("我是普通的click事件");
    })
    $("div").bind("click.muke",1)">(){
        console.log("我是click.muke的事件");
    })

    $("div").unbind(".muke" 绑定多个事件
    $("div").bind("click",1)">(){
        console.log(111)
    }).bind("touchstart",1)">(){
        console.log(222)
    })

动画

    $('button').on('click',1)">(){
        $('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,1)">(){
        alert("动画执行完毕");
    })

Ajax

     Ajax(){
        var xmlHttpReq = null;
        if(window.ActiveXObject){
             兼容IE5、IE6
            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
        }else{
            xmlHttpReq = new XMLHttpRequest();
        }

        xmlHttpReq.open("GET","test.php",1)">true);
        xmlHttpReq.onreadystatechange = RequestCallBack;

         RequestCallBack(){
            if(xmlHttpReq.readyState == 4){
                if(xmlHttpReq.status == 200){
                    console.log("获取数据:"+xmlHttpReq.responseText);
                }
            }
        }
        xmlHttpReq.send();
    }

ajax请求

     get
    $.get('urlxxx',1)">(response){
      $(document.body).append(response)
    });

     post
    $.post('urlxxx',{ sample: 'payload' },1)">(response){
         
    });
    
     ajax
    $.ajax({
      type: 'GET''Zepto.js' },dataType: 'json'(data){
        this.append(data.project.html)
      },error: (xhr,type){
        alert('Ajax error!')
      }
    })

touch模块
先引入touch.js

  <script type="text/javascript" src="../../lib/touch.js"></script>

touch.js

;(($){
  var touch = {},touchTimeout,tapTimeout,swipeTimeout,longTapTimeout,longTapDelay = 750 swipeDirection(x1,x2,y1,y2) {
    return Math.abs(x1 - x2) >=
      Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
  }

   longTap() {
    longTapTimeout = null
     (touch.last) {
      touch.el.trigger('longTap')
      touch = {}
    }
  }

   cancelLongTap() {
     (longTapTimeout) clearTimeout(longTapTimeout)
    longTapTimeout = 
  }

   cancelAll() {
     (touchTimeout) clearTimeout(touchTimeout)
     (tapTimeout) clearTimeout(tapTimeout)
     (swipeTimeout) clearTimeout(swipeTimeout)
     (longTapTimeout) clearTimeout(longTapTimeout)
    touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = 
    touch = {}
  }

   isPrimaryTouch(event){
    return (event.pointerType == 'touch' ||
      event.pointerType == event.MSPOINTER_TYPE_TOUCH)
      && event.isPrimary
  }

   isPointerEventType(e,type){
    return (e.type == 'pointer'+type ||
      e.type.toLowerCase() == 'mspointer'+type)
  }

  $(document).ready(var now,delta,deltaX = 0,deltaY = 0if ('MSGesture' in window) {
      gesture =  MSGesture()
      gesture.target = document.body
    }

    $(document)
      .bind('MSGestureEnd',1)">(e){
        var swipeDirectionFromVelocity =
          e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null
         (swipeDirectionFromVelocity) {
          touch.el.trigger('swipe')
          touch.el.trigger('swipe'+ swipeDirectionFromVelocity)
        }
      })
      .on('touchstart MSPointerDown pointerdown',1)">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 = 
        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','move')) &&
          !isPrimaryTouch(e)) ]
        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','up')) &&
          !isPrimaryTouch(e)) 
        cancelLongTap()

         swipe
        if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
            (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))

          swipeTimeout = setTimeout(() {
             (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'  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(() {

               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
               (touch.el) touch.el.trigger(event)

               trigger double tap immediately
               (touch.isDoubleTap) {
                if (touch.el) touch.el.trigger('doubleTap')
                touch = {}
              }

               trigger single tap after 250ms of inactivity
               {
                touchTimeout = setTimeout((){
                  touchTimeout = null
                  if (touch.el) touch.el.trigger('singleTap')
                  touch = {}
                },250)
              }
            },1)">)
          }  {
            touch = {}
          }
          deltaX = deltaY = 0

      })
       when the browser window loses focus,
       for example when a modal dialog is shown,1)"> cancel all ongoing events
      .on('touchcancel MSPointerCancel pointercancel' scrolling the window indicates intention of the user
     to scroll,not tap or swipe,so cancel all ongoing events
    $(window).on('scroll''doubleTap','tap','singleTap','longTap'].forEach((eventName){
    $.fn[eventName] = function(callback){ return .on(eventName,callback) }
  })
})(Zepto)

使用时:

  <script>
  $(document).ready((){
    $('#touch_test').bind('touchmove',1)">(e) { e.preventDefault() })
    
    listen_to('#touch_test')
    
     listen_to(el) {
      $(el).tap((){
        console.log(' | tap!')
      })
      .doubleTap((){
        console.log(' | double tap!')
      })
      .swipe((){
        console.log(' | swipe!')
      })
      .swipeLeft((){
        console.log(' | swipe left!')
      })
      .swipeRight((){
        console.log(' | swipe right!')
      })
      .swipeUp((){
        console.log(' | swipe up!')
      })
      .swipeDown((){
        console.log(' | swipe down!')
      })
      .longTap((){
        console.log(' | long tap!')
      })
      .singleTap((){
        console.log(' | single tap!')
      })
    }
  }); 
  </script>

插件的写法
先编写自定义插件js文件
zepto.color.js

;(($){
    一个插件的写法
    $.fn.color = (option){
        var options = $.extend({
            col: "blue"
        },option);

        this.css("color"this.css("fontSize";
    }
})(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>

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...