检测触摸和点击事件的更好方法

3
所以,我已经经历了很多次代码迭代,但我认为我终于想出了一种使用通用jQuery插件来检测点击与轻敲事件的终极方法。该插件需要一个隐藏的输入字段来存储“touchMove”标志。有没有人知道一种(查看我的代码)将标志存储在全局变量中的方法?我尝试声明一个全局touchMove变量,但不幸的是,JavaScript函数会将全局变量复制到作用域内的本地副本中。
无论如何,这就是我得到的内容:

$(document).ready(function() {
  $("#touch-me").touch(function() {
    console.log("I have been activated!");
  });
});

$.fn.touch = function(callback) {
  var touch = false;
  $(this).on("click", function(e) {
    if (!touch) {
      console.log("I click!");
      let callbackReal = callback.bind(this);
      callbackReal(this, e);
    } else {
      touch = true;
    }
    touch = false;
  });
  $(this).on("touchend", function(e) {
    $(this).blur();
    if (typeof e.touches != typeof undefined) {
      e.preventDefault();
      touch = true;
      if ($("#touchMove").val() == 'moved') {
        console.log("You moved your finger, so I quit!");
        $("#touchMove").val('');
        return false;
      } else {
        console.log("I touch!");
        let callbackReal = callback.bind(this);
        callbackReal(this, e);
      }
    }
  });
  $(this).on("touchmove", function(e) {
    $("#touchMove").val('moved');
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="touch-me">Touch or Click on ME</button>
<input type="hidden" id="touchMove" value="" />

我在GitHub上也有我的代码:https://github.com/cloudmedia/jQuery.touch.js,这是一个与IT技术相关的项目。同时,我还分享了一个fiddle演示:https://jsfiddle.net/cloudulus/7n9deqxb/。如果您有任何改进建议,欢迎提出。请注意,本文中涉及的所有html标签均已保留。

你可以随时使用window.touchMove=true来设置任何全局变量。 - undefined
确实,你可以这样做,但是在全局声明单独的变量会显得有些混乱。由于jQuery本身就是一个对象,你也可以使用$.touchMove来避免进一步混杂window对象。 - undefined
1
谢谢,@Shikkediel。我不知道你可以像那样访问jQuery的属性!多么简单,却非常有用。真不敢相信我以前竟然不知道这个。过去我所做的所有变通方法...我把你的建议放在了我的答案中。 - undefined
1个回答

3

以下是由@Shikkediel编辑的最终代码:

$.fn.touch = function(callback) {

  $.touch = {
    action: "",
    move: false,
    event: false
  }

  return this.on("click", function(e) {
      if (!$.touch.event) {
        $.touch.action = "click";
        let callbackReal = callback.bind(this);
        callbackReal(this, e);
      }
      $.touch.event = false;
    })
    .on("touchend", function(e) {
      $(this).blur();
      $.touch.event = true;
      if ($.touch.move) {
        $.touch.move = false;
        return;
      } else {
        $.touch.action = "touch";
        let callbackReal = callback.bind(this);
        callbackReal(this, e);
      }
    })
    .on("touchmove", function() {
      $.touch.move = true;
    });
}

$("#clickme").touch(function() {
  console.log("Action: " + $.touch.action);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="clickme">Click or Touch Me!</button>

干得好,Shikkediel。谢谢!


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