PC鼠标拖动滑块 转变为 手机手指滑动滑块

来源:互联网 发布:电脑显示器改网络电视 编辑:程序博客网 时间:2024/05/01 20:48

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
才能真正实现移动端滑块随手指滑动。

0 0