移动设备/触摸屏-在滑动时进行水平滚动

4

这个问题是在这个SO问题的详细讨论后提出的。

问题:

我需要一个水平滚动条,可以在桌面上使用鼠标拖动,在触摸屏上使用滑动事件进行滚动。

可能的解决方案:

我尝试使用jQuery dragscrollable,在桌面上工作正常,但在触摸设备上无法使用。

然后我开始探索Touch Swipe Jquery Plugin,并提出了一个可能的解决方案JSFiddle Code,JSFiddle的结果可以在这里找到。

你也可以在这里找到一个工作演示。

我的JavaScript代码如下:

//to detect if device has touch enabled
var is_touch_device = 'ontouchstart' in document.documentElement;

        $(function() 
        {
                $('.myClass').dragscrollable();
                //if touch is enabled then we have to map the swipe event                         
                if(is_touch_device)
                    $('.panel_list').swipe( { swipeStatus:scroll_panel_list, allowPageScroll:'horizontal' } );
                function scroll_panel_list(event, phase, direction, distance)
                {
                    var pos = $('.myClass').scrollLeft();
                    if(direction == 'left')
                    {
                        $('.myClass').animate({scrollLeft: pos + 200} );
                    }
                    if(direction == 'right')
                    {
                        $('.myClass').animate({scrollLeft: pos - 200} );
                    }
                }    
            });​

我已经测试了它在Android浏览器上运行良好,但在iPhone上响应不太灵敏。有人能帮我想出更好的解决方案吗?我正在使用Twitter Bootstrap。
编辑:1
现在我想我可能找到了一个很好的插件,它似乎在台式机和触摸设备上都能正常工作,该插件称为jquery.dragscroll,我更新了演示here
编辑:2
似乎还有另一个支持触摸设备的插件,它被称为Overscroll。我还没有评估过它。

在 Windows Phone 7 上也不能工作。 - Sherbrow
@Sherbrow,就目前而言,如果它主要适用于iOS设备和Android设备,我会非常高兴!!请查看我的更新解决方案,并让我知道您的想法!! - Anand Sunderraman
这个问题的被接受答案指向了一个失效链接。 - mawcsco
3个回答

2
我找到了一个较旧的解决方案,并对其进行了修改以实现水平滚动。我已在Android Chrome和iOS Safari上进行了测试,由于监听器触摸事件已经存在很长时间了,因此具有良好的支持:http://caniuse.com/#feat=touch用法:
touchHorizScroll('divIDtoScroll');

功能:

function touchHorizScroll(id){
    if(isTouchDevice()){ //if touch events exist...
        var el=document.getElementById(id);
        var scrollStartPos=0;

        document.getElementById(id).addEventListener("touchstart", function(event) {
            scrollStartPos=this.scrollLeft+event.touches[0].pageX;              
        },false);

        document.getElementById(id).addEventListener("touchmove", function(event) {
            this.scrollLeft=scrollStartPos-event.touches[0].pageX;              
        },false);
    }
}
function isTouchDevice(){
    try{
        document.createEvent("TouchEvent");
        return true;
    }catch(e){
        return false;
    }
}   

原始的垂直单指触摸滚动:

http://chris-barr.com/2010/05/scrolling_a_overflowauto_element_on_a_touch_screen_device/

现在,垂直方向有一个简化的CSS解决方案,但在移动设备上无法用于水平DIV滚动:

-webkit-overflow-scrolling: touch

该问题还要求在桌面上进行鼠标抓取,可以使用Nice Scroll实现,并且如果需要,它可以与我上面提供的解决方案一起使用: https://github.com/inuyaksa/jquery.nicescroll
var nice = $("#mydiv").getNiceScroll({horizrailenabled: true, hwacceleration: true});

2

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接