移動端touchstart,touchmove,touchend


近段時間使用html5開發一個公司內部應用,而觸摸事件必然是移動應用中所必須的,剛開始以為移動設備上或許也會支持鼠標事件,原來是不支持的,好在webkit內核的移動瀏覽器支持touch事件,並且打包成app也毫無壓力。原本以為touch事件應該跟鼠標事件是一樣的道理,實踐過程中雖然不難,但還是碰到了不少坑,才發現還是略有區別的。

$(document).bind(touchEvents.touchstart, function (event) {
            event.preventDefault();
            
        });
        $(document).bind(touchEvents.touchmove, function (event) {
            event.preventDefault();
            
        });

        $(document).bind(touchEvents.touchend, function (event) {
            event.preventDefault();
            
        });

 

很多博文中稱touch的三個事件都有targetTouches,touches以及changedTouches對象列表,其實不然,touchend事件中應該是只有個changedTouches觸摸實例列表的,而且這里說明一下,回調函數的event只是一個普通的object對象,實際上event中有一個originalEvent屬性,這才是真正的touch事件,這個事件中才存在着上訴三個觸摸實例列表,這三個實例存儲了觸摸事件的位置等等屬性,類似於鼠標事件。其他地方基本與鼠標事件是一致的。簡單介紹一下這三個觸摸列表,touches是在屏幕上的所有手指列表,targetTouches是當前DOM上的手指列表,所以當手指移開觸發touchend事件時,event.originalEvent是沒有這個targetTouches列表的,而changedTouches列表是涉及當前事件的列表,例如touchend事件中,手指移開。接下來談談pc與移動端的適配問題,既然使用html5,當然是看中他的跨平台特性了,不僅僅要ios和android適配,pc上直接打開網頁最好也是可以的,但是pc上只支持鼠標事件怎么辦。好辦,仔細觀察上面代碼的觸摸事件,touchEvents.touchXXX,看如下代碼:

 

var touchEvents = {
        touchstart: "touchstart",
        touchmove: "touchmove",
        touchend: "touchend",

        /**
         * @desc:判斷是否pc設備,若是pc,需要更改touch事件為鼠標事件,否則默認觸摸事件
         */
        initTouchEvents: function () {
            if (isPC()) {
                this.touchstart = "mousedown";
                this.touchmove = "mousemove";
                this.touchend = "mouseup";
            }
        }
    };


若在pc上,則使用鼠標事件,在移動設備中,就使用觸摸事件,就這么簡單,判斷是否pc也很方便,就不做多解釋了。

 

 

 

 

demo

var praiseBtn=document.querySelector('.praiseBtn');//獲取div
        praiseBtn.addEventListener("touchstart",StartPraiseBtn,false);//添加觸摸事件
        praiseBtn.addEventListener("touchend",StopPraiseBtn,false);//添加觸摸事件
        //touchstart
        function StartPraiseBtn()
        {
            document.querySelector('.praiseBtn').className="praiseBtn current";//添加open類
        }
        //touchend
        function StopPraiseBtn()
        {
            document.querySelector('.praiseBtn').className="praiseBtn current";
        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM