prevent touchstart when swiping

前端 未结 11 2077
萌比男神i
萌比男神i 2020-11-30 20:09

I have a scrollable list on a mobile device. They want people to be able to scroll the list via swiping, and also select a row by tapping.

The catch is combining th

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 21:09

    Here's what I eventually came up with to allow for a list of items to be scrollable via swipe, but also each item to be 'triggerable' via a tap. In addition, you can still use with a keyboard (using onclick).

    I think this is similar to Netlight_Digital_Media's answer. I need to study that one a bit more.

    $(document)
    // log the position of the touchstart interaction
    .bind('touchstart', function(e){ 
      touchStartPos = $(window).scrollTop();
    })
    // log the position of the touchend interaction
    .bind('touchend', function(e){
      // calculate how far the page has moved between
      // touchstart and end. 
      var distance = touchStartPos - $(window).scrollTop();
    
      var $clickableItem; // the item I want to be clickable if it's NOT a swipe
    
      // adding this class for devices that
      // will trigger a click event after
      // the touchend event finishes. This 
      // tells the click event that we've 
      // already done things so don't repeat
    
      $clickableItem.addClass("touched");      
    
      if (distance > 20 || distance < -20){
            // the distance was more than 20px
            // so we're assuming they intended
            // to swipe to scroll the list and
            // not selecting a row. 
        } else {
            // we'll assume it was a tap 
            whateverFunctionYouWantToTriggerOnTapOrClick()
        }
    });
    
    
    $($clickableItem).live('click',function(e){
     // for any non-touch device, we need 
     // to still apply a click event
     // but we'll first check to see
     // if there was a previous touch
     // event by checking for the class
     // that was left by the touch event.
    if ($(this).hasClass("touched")){
      // this item's event was already triggered via touch
      // so we won't call the function and reset this for
      // the next touch by removing the class
      $(this).removeClass("touched");
    } else {
      // there wasn't a touch event. We're
      // instead using a mouse or keyboard
      whateverFunctionYouWantToTriggerOnTapOrClick()
    }
    });
    

提交回复
热议问题