所以,我已经经历了很多次代码迭代,但我认为我终于想出了一种使用通用jQuery插件来检测点击与轻敲事件的终极方法。该插件需要一个隐藏的输入字段来存储“touchMove”标志。有没有人知道一种(查看我的代码)将标志存储在全局变量中的方法?我尝试声明一个全局
无论如何,这就是我得到的内容:
我在GitHub上也有我的代码:https://github.com/cloudmedia/jQuery.touch.js,这是一个与IT技术相关的项目。同时,我还分享了一个fiddle演示:https://jsfiddle.net/cloudulus/7n9deqxb/。如果您有任何改进建议,欢迎提出。请注意,本文中涉及的所有html标签均已保留。
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="" />
window.touchMove=true
来设置任何全局变量。 - undefined$.touchMove
来避免进一步混杂window对象。 - undefined