因此,我经历了代码的许多迭代,但是我想我终于想出了使用通用jQuery插件检测click vs tap事件的终极方法。该插件需要一个隐藏的输入字段来存储“ 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
这是一个小提琴: https://jsfiddle.net/cloudulus/7n9deqxb/
任何改进我的代码的建议将不胜感激。
答案 0 :(得分:1)
这是@Shikkediel编辑的最终代码:
import Players as pl
dealer = pl.Dealer()
dealer.deck_shuffle()
$.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);
});
干得好,Shikkediel。谢谢!