PC鼠標拖動滑塊 轉變爲 手機手指滑動滑塊

PC鼠標拖動滑塊 轉變爲 手機手指滑動滑塊

在PC端可以用mousedown來觸發一個滑塊滑動的效果,但在手機上,貌似無法識別這個事件,但手機上有touchstart事件,可以通過一系列“touch”事件來替代PC端的“mouse”事件。

原來的 PC端 使用的代碼:

var mousex = 0;
var divLeft;

//觸發滑塊拖動
$('#rangeBtn').bind('mousedown',function(e){
    mousex = e.pageX;
    divLeft = $(this).position().left;
    //綁定滑塊移動事件
    $(this).bind('mousemove',dragElement);
});

//結束滑塊移動
$(document).bind('mouseup',function(){
    $('#rangeBtn').unbind('mousemove');
});

/**
 * 函數:拖動滑塊
**/
function dragElement(event) {
    var left = divLeft + (event.pageX - mousex);
    if (left < 0) {
        left = 0;
    } else if (left > width) {
        left = width;
    }
    $(this).css({'left' : left + 'px'});
    return false;
}

轉變爲 移動端 使用的代碼:

var mousex = 0;
var divLeft;

//觸發滑塊拖動
$('#rangeBtn').bind('touchstart',function(e){
    mousex = e.originalEvent.targetTouches[0].pageX;
    divLeft = $(this).position().left;
    //綁定滑塊移動事件
    $(this).bind('touchmove',dragElement);
});

//結束滑塊移動
$(document).bind('touchend',function(){
    $('#rangeBtn').unbind('touchmove');
});

/**
 * 函數:拖動滑塊
**/
function dragElement(event) {
    var left = divLeft + (event.originalEvent.targetTouches[0].pageX - mousex);
    if (left < 0) {
        left = 0;
    } else if (left > width) {
        left = width;
    }
    $(this).css({'left' : left + 'px'});
    return false;
}

比較兩段代碼可以輕易看出:
- touchstart 對應 mousedown
- touchmove 對應 mousemove
- mouseup 對應 touchend
但是,如果只切換這三個單詞並沒有實現滑動效果,探究了很長時間後發現要將
- e.pageX 切換成 e.originalEvent.targetTouches[0].pageX
才能真正實現移動端滑塊隨手指滑動。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章