开发者

Listening for javascript touch events but still allowing default scrolling behaviour

开发者 https://www.devze.com 2023-01-15 10:41 出处:网络
I am trying to implement a scrollable element for a mobile app and it looks like you must use preventDefault on the initial touchStart event, otherwise the browser will not fire all the touchMove even

I am trying to implement a scrollable element for a mobile app and it looks like you must use preventDefault on the initial touchStart event, otherwise the browser will not fire all the touchMove events 开发者_开发百科(presumably for performance reasons).

So it would seem that if I want to allow touch scrolling on an overflown element, the user will not be able to scroll the page as per usual when touching that element. This is problematic if the overflown element takes up a large portion of the viewport.

Is their a workaround for this?


Take a look at this library

http://api.mutado.com/mobile/mtdtouch/js/

The "core" javascript includes a base UIComponent optimized for touch events (webkit). The UI.Scroll component in example manage the "prevent default issue" for you.

Try to subclass the UIComponent and implement your own events handler like this

$MTD.YourOwnComponent = $.klass( $MTD.UIComponent, {    

    touchesBegan: function( e ) {
        // your stuff
    },

    touchesMoved: function( e ) {
        // your stuff   
    },

    touchesEnded: function( e ) {
        // your stuff
    }

});

Hope this helps.


Here's a simple workaround: drop the touchstart handler. You can reconstruct most of what's going on with just the touchmove, touchend, and touchleaving handlers.

In the browser I tested with (Chrome), scrolling happens as long as you don't have a touchstart handler; it doesn't care about the other ones. As long as you aren't actively calling ev.preventDefault in the touchmove handlers, scrolling works.

Assuming what you want to do will work fine despite only finding out about a touch when the finger starts moving, instead of when the finger initially lands, this workaround should work acceptably.

... And also I'm assuming other browsers use the same logic as Chrome.

0

精彩评论

暂无评论...
验证码 换一张
取 消