向下滑动2次时发出警报

时间:2019-01-27 15:23:48

标签: jquery jquery-mobile

当用户在移动设备上向上滚动(或向下滑动)特定px值或连续2次时,我想提醒一条消息。

我已经有了使用jquery mobile的可行解决方案,但是它非常敏感。因此,当我向上滚动(向下滑动)几个像素时,感觉就像是在触发。总体目标是,当用户尝试用鼠标在桌面上关闭标签页/浏览器时,找到与触发器类似的内容。所以我想,如果用户向上滚动几个特定的​​像素值或x倍,这是一个信号,表明应该发生某些事情,或者他会离开网站。

我在jquery mobile上尝试过,这是我的codepen: https://codepen.io/maximilian-neuse/pen/KJzQzM

$.support.touch = true;
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 < 2000 &&
              Math.abs(start.coords[1] - stop.coords[1]) > 10 &&
              Math.abs(start.coords[0] - stop.coords[0]) < 400
            ) {
              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);
      }
    };
  }
);

$("body").on("swipedown", function() {
  if (popupCounter < 1) {
    alert("dont leave!");
  }
  popupCounter++;
});

那么,我该如何降低它的敏感性?还是有更好的解决方案来触发这样的动作?

0 个答案:

没有答案