2013-06-16 2 views
27

Я пытаюсь сделать мероприятие по экрану вверх и вниз, а левая и праваяКак сильно ударить сверху вниз JQuery мобильный

у меня есть этот бросок, как изображение показывает: how to make swipe top down

Я могу обрабатывать событие используя значок стрелки (onClick()), но я хочу добавить салфетки вверх, событие при добавлении события салфетки, которое оно работает слева направо. . Я хочу, чтобы он отображался вверх, как показано на картинке любая помощь?

ответ

51

jQuery Mobile изначально предоставляет нам возможность захватывать swipeleft и swiperight. Тем не менее, он не предлагает нам прокручивать и вытаскивать из коробки. Адаптируя то, что команда jQuery сделала для swipeleft и swiperight, мы можем создавать и фиксировать эти события таким же образом. Смотрите следующий код для реализации swipeup и swipedown:

(function() { 
    var supportTouch = $.support.touch, 
      scrollEvent = "touchmove scroll", 
      touchStartEvent = supportTouch ? "touchstart" : "mousedown", 
      touchStopEvent = supportTouch ? "touchend" : "mouseup", 
      touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; 
    $.event.special.swipeupdown = { 
     setup: function() { 
      var thisObject = this; 
      var $this = $(thisObject); 
      $this.bind(touchStartEvent, function(event) { 
       var data = event.originalEvent.touches ? 
         event.originalEvent.touches[ 0 ] : 
         event, 
         start = { 
          time: (new Date).getTime(), 
          coords: [ data.pageX, data.pageY ], 
          origin: $(event.target) 
         }, 
         stop; 

       function moveHandler(event) { 
        if (!start) { 
         return; 
        } 
        var data = event.originalEvent.touches ? 
          event.originalEvent.touches[ 0 ] : 
          event; 
        stop = { 
         time: (new Date).getTime(), 
         coords: [ data.pageX, data.pageY ] 
        }; 

        // prevent scrolling 
        if (Math.abs(start.coords[1] - stop.coords[1]) > 10) { 
         event.preventDefault(); 
        } 
       } 
       $this 
         .bind(touchMoveEvent, moveHandler) 
         .one(touchStopEvent, function(event) { 
        $this.unbind(touchMoveEvent, moveHandler); 
        if (start && stop) { 
         if (stop.time - start.time < 1000 && 
           Math.abs(start.coords[1] - stop.coords[1]) > 30 && 
           Math.abs(start.coords[0] - stop.coords[0]) < 75) { 
          start.origin 
            .trigger("swipeupdown") 
            .trigger(start.coords[1] > stop.coords[1] ? "swipeup" : "swipedown"); 
         } 
        } 
        start = stop = undefined; 
       }); 
      }); 
     } 
    }; 
    $.each({ 
     swipedown: "swipeupdown", 
     swipeup: "swipeupdown" 
    }, function(event, sourceEvent){ 
     $.event.special[event] = { 
      setup: function(){ 
       $(this).bind(sourceEvent, $.noop); 
      } 
     }; 
    }); 

})(); 

и вот ответ от Blackdynamo

+1

это точно что я хочу, и это сработало для меня. – Muath

+0

Как настроить прослушиватель для события swipeupdown и выполнить различные задачи для события swipeup и swipedown? –

+3

@SantoshGhimire, вы можете использовать '$ ('mySelector'). On ('swipeup', function() {});' и '$ ('mySelector'). On ('swipedown', function() {}) ; ' – Turnerj

1

У меня были проблемы с принятым ответ здесь, потому что ударяя не был обнаружен, когда происхождение и цель прикосновением не были одинаковыми.

Здесь может быть проще ответ, где я непосредственно переопределить событие JQuery handleSwipe (на основе jquery.mobile-1.4.5) и добавить его с вертикальным движением, называется вверх и вниз:

(function($, window, undefined) { 

    //custom handleSwipe with swiperight, swipeleft, swipeup, swipedown 
    $.event.special.swipe.handleSwipe = function(start, stop, thisObject, origTarget) { 
     if (stop.time - start.time < $.event.special.swipe.durationThreshold) { 
      var horSwipe = Math.abs(start.coords[0] - stop.coords[0]) > $.event.special.swipe.horizontalDistanceThreshold; 
      var verSwipe = Math.abs(start.coords[1] - stop.coords[1]) > $.event.special.swipe.verticalDistanceThreshold; 
      if(horSwipe != verSwipe) { 
       var direction; 
       if(horSwipe) 
        direction = start.coords[0] > stop.coords[0] ? "swipeleft" : "swiperight"; 
       else 
        direction = start.coords[1] > stop.coords[1] ? "swipeup" : "swipedown"; 
       $.event.trigger($.Event("swipe", { target: origTarget, swipestart: start, swipestop: stop }), undefined, thisObject); 
       $.event.trigger($.Event(direction, { target: origTarget, swipestart: start, swipestop: stop }), undefined, thisObject); 
       return true; 
      } 
      return false; 
     } 
     return false; 
    } 

    //do binding 
    $.each({ 
     swipeup: "swipe.up", 
     swipedown: "swipe.down" 
    }, function(event, sourceEvent) { 
     $.event.special[ event ] = { 
      setup: function() { 
       $(this).bind(sourceEvent, $.noop); 
      }, 
      teardown: function() { 
       $(this).unbind(sourceEvent); 
      } 
     }; 
    }); 
})(jQuery, this); 
+0

«принятый ответ сработал отлично» и 50 человек проголосовали в этом сообществе – Muath

+0

http://stackoverflow.com/questions/19808917/how-to-get-swipe-up-and-swipe-down-event-in -jquery-mobile/21644139 # 21644139 – Muath

+0

см. этот рабочий пример на нем – Muath

Смежные вопросы