js-touch

//touchstart:  // 手指放到屏幕上的时候触发 

//touchmove:  // 手指在屏幕上移动的时候触发 


function touchStart(event) {
         event.preventDefault();
         if (spirit ||! event.touches.length) return;
         var touch = event.touches[0];
         startX = touch.pageX;
         startY = touch.pageY;
         spirit = document.createElement(“div”);
         spirit.className = “spirit”;
         spirit.style.left = startX;
         spirit.style.top = startY;
         canvas.appendChild(spirit);
}
function touchMove(event) {
         event.preventDefault();
         if (!spirit || !event.touches.length) return;
         var touch = event.touches[0],
              x = touch.pageX – startX,
              y = touch.pageY – startY;
         spirit.style.webkitTransform = 'translate(' + x + 'px, ' + y + 'px)';     
}
简易touch

 

(function(window) {

    try {
        document.createEvent('TouchEvent');
        return;
    }
    catch(e) {
    }
    var eventMap = {
        'mousedown': 'touchstart',
        'mouseup':   'touchend',
        'mousemove': 'touchmove'
    };

    var initialize = function() {
        for (var key in eventMap) {
                     document.body.addEventListener(key, function(e) {
                     var event = createTouchEvent(eventMap[e.type], e);
                e.target.dispatchEvent(event);
               var fn = e.target['on' + eventMap[e.type]];
                if (typeof fn === 'function') fn(e);
            }, false);
        }
    };

    var createTouchEvent = function(name, e) {
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent(
            name,
            e.bubbles,
            e.cancelable,
            e.view,
            e.detail,
            e.screenX,
            e.screenY,
            e.clientX,
            e.clientY,
            e.ctrlKey,
            e.altKey,
            e.shiftKey,
            e.metaKey,
            e.button,
            e.relatedTarget
        );

        return event;
    };
    if (document.readyState === 'complete' || document.readyState === 'loaded') {
        initialize();
    }
    else {
        window.addEventListener('load', initialize, false);
    }

})(window);
移动设备与web通用

 

posted @ 2013-11-13 09:31  琦琦狐  阅读(317)  评论(0编辑  收藏  举报