在我的HTML中,有一个可以短按和长按的按钮。如果你很快点击它(就像在其他每个按钮上一样)它会执行一个给定的回调函数。当您持续按下按钮时,将重复执行回调,直到检测到mouseup或mouseout事件。
var onBtnClick = function (evt, callback) {
//only react to left mouse button
if (evt.which == 1) {
//save 'this' context and interval/timeout IDs
var self = this,
interval= null,
timeout = null;
//react to a single click
callback();
//when user leaves the button cancel timeout/interval, lose focus and unbind recently bound listeners
self.on("mouseup mouseout", function () {
window.clearTimeout(timeout);
window.clearInterval(interval);
self.blur();
self.off("mouseup mouseout");
});
//on a long click call the callback function within an interval for faster value changing
timeout = window.setTimeout(function () {
interval = window.setInterval(callback, 50);
}, 300);
}
},
i = 0,
cb = function () {
console.log(i++);
};
$("button").mousedown(function(evt) {
onBtnClick.call($(this), evt, cb);
});
这适用于桌面环境。但是:在移动设备上使用网站时,长按不会被注册,因为浏览器会检测到右键单击(长按)。
是否可以在移动设备上重新创建桌面行为?我怎么能实现这个目标?
答案 0 :(得分:1)
您希望在移动设备中加入Convert(varchar(10),cast(vr.RegDate as DATETIME),105) as RegistrationDate
和touchstart
个活动。此外,您还需要确保为其提供的功能包括对touchend
的调用。这样做有效地告诉移动浏览器"嘿,你知道你现在通常想做的事吗?不要这样做。"
也就是说,您提供的代码的更新版本应如下所示:
evt.preventDefault()
主要更改:在if检查中添加了var onBtnClick = function (evt, callback) {
//only react to left mouse button or a touch event
if (evt.which == 1 || evt.type == "touchstart") {
//save 'this' context and interval/timeout IDs
var self = this,
interval= null,
timeout = null;
//react to a single click
callback();
//when user leaves the button cancel timeout/interval, lose focus and unbind recently bound listeners
self.on("mouseup mouseout touchend", function (evt) {
window.clearTimeout(timeout);
window.clearInterval(interval);
self.blur();
self.off("mouseup mouseout touchend");
evt.preventDefault();
});
//on a long click call the callback function within an interval for faster value changing
timeout = window.setTimeout(function () {
interval = window.setInterval(callback, 50);
}, 300);
}
},
i = 0,
cb = function () {
console.log(i++);
};
$("button").mousedown(function(evt) {
onBtnClick.call($(this), evt, cb);
});
$('#hold').on('touchstart', function (evt) {
onBtnClick.call($(this), evt, cb);
evt.preventDefault();
});
,以便捕获鼠标左键和触摸事件,并将|| evt.type == "touchstart"
添加到touchend
和mouseup
事件列表中,将mouseout
添加到清除超时的函数中,并添加了evt.preventDefault()
jQuery调用,以确保您的按钮实际上专门用于触摸和点击。