天天看點

移動端的事件庫

FastClick.js:解決click事件300ms的延遲

touch.js:百度雲手勢事件庫   

GitHub位址:https://github.com/Clouda-team/touch.code.baidu.com

移動端的事件庫
移動端的事件庫
移動端的事件庫

實戰touch.js

首先要引入touch.js

再實作事件的綁定

<body>  
<div class="box"></div>  
<script type="text/javascript" src="js/touch-0.2.14.min.js"></script>  
<script type="text/javascript">  
    var box = document.querySelector('.box');  
//    當單擊螢幕,順時針旋轉360度  
    touch.on(box, 'tap', function (ev) {  
        this.style.webkitTransitionDuration = '1s';  
        this.style.webkitTransform = 'rotate(360deg)';  
        var timer = window.setTimeout(function () {  
            this.style.webkitTransitionDuration = '0s';  
            this.style.webkitTransform = 'rotate(0deg)';  
            window.clearTimeout(timer);  
        }.bind(this),1000);  
    });  
//    當輕按兩下螢幕,逆時針旋轉360度  
    touch.on(box, 'doubletap',function (ev) {  
       this.style.webkitTransitionDuration = '1s';  
       this.style.webkitTransform = 'rotate(-360deg)';  
       var timer = window.setTimeout(function () {  
           this.style.webkitTransitionDuration = '0s';  
           this.style.webkitTransform = 'rotate(0deg)';  
           window.clearTimeout(timer);  
       }.bind(this),1000);  
    });  
//    當長按和滑動的時候,盒子的背景顔色變紅  
    touch.on(box,'hold swipe',function (ev) {  
        this.style.backgroundColor = 'red';  
    })  
</script>  
</body>
           

hammer.js:多點觸控插件。官網:http://hammerjs.github.io/

hammer.js在使用時非常簡單,代碼示例如下:

<div id="test" class="test"></div>  
<script type="text/javascript">  
     //建立一個新的hammer對象并且在初始化時指定要處理的dom元素  
     var hammertime = new Hammer(document.getElementById("test"));  
     //為該dom元素指定觸屏移動事件  
     hammertime.on("pan", function (ev) {  
          //控制台輸出  
          console.log(ev);  
     });  
</script>
           

Zepto.js:被譽為移動端的小型jQuery

GitHub位址:https://github.com/madrobby/zepto

api文檔位址:http://www.css88.com/doc/zeptojs_api/

jQuery由于是在PC端使用的,是以代碼中包含了大量的對于IE低版本的相容處理,而zepto值應用于移動端開發,是以在jQuery的基礎上沒有對低版本的IE進行支援

jQuery中提供了很多的選擇器類型及DOM操作方法,但是zepto中隻是實作了部分常用的選擇器和方法,例如:jQuery中的動畫方法有animate,show,hide,toggle,fadeIn,fadeOut,fadeToggle,slideUp,slideDown,slideToggle...但是zepto中隻有animate

是以,zepto的源代碼比jQuery小很多。

zepto專門為移動端開發而誕生,是以相對于jQuery來說更适合移動端、

zepto的animate動畫方法支援了CSS3動畫的操作

zepto專門準備了移動端常用的事件操作:tap點選,singleTap單擊,doubleTap輕按兩下,longTap長按,sswipe滑動,swipeUp上滑,swipeDown下滑,swipeLeft左滑,swipeRight右滑....

<script type="text/javascript" src="js/zepto.min.js"></script>  
<script type="text/javascript">  
    $('.box').singleTap(function (ev) {  
        $(this).animate({  
            rotate: '360deg'  
        }, 1000, 'linear', function () {  
            this.style.webkitTransform = 'rotate(0deg)';  
        })  
    }).on('touchstart', function () {  
        $(this).css('background', 'red');  
    });  
</script>