如何使用 android 和 iphone 的 javascript 检测长触摸压力?本机 javascript 或 jquery ...
我想要的东西听起来像:
<input type='button' onLongTouch='myFunc();' />
如何使用 android 和 iphone 的 javascript 检测长触摸压力?本机 javascript 或 jquery ...
我想要的东西听起来像:
<input type='button' onLongTouch='myFunc();' />
使用 Touch End 检测长触摸的问题在于,如果您希望事件在一段时间后触发,它将无法工作。最好在触摸开始时使用计时器并在触摸结束时清除事件计时器。可以使用以下模式:
var onlongtouch;
var timer;
var touchduration = 500; //length of time we want the user to touch before we do something
touchstart() {
timer = setTimeout(onlongtouch, touchduration);
}
touchend() {
//stops short touches from firing the event
if (timer)
clearTimeout(timer); // clearTimeout, not cleartimeout..
}
onlongtouch = function() { //do something };
这是 Joshua 答案的扩展版本,因为他的代码运行良好,直到用户不执行多点触控(您可以用两根手指点击屏幕,功能将被触发两次,4 根手指 - 4 次)。在一些额外的测试场景之后,我什至触发了非常频繁地触摸并在每次点击后接收执行的功能的可能性。
我添加了一个名为“lockTimer”的变量,它应该在用户触发“touchend”之前锁定任何额外的 touchstarts。
var onlongtouch;
var timer;
var touchduration = 800; //length of time we want the user to touch before we do something
function touchstart(e) {
e.preventDefault();
if (!timer) {
timer = setTimeout(onlongtouch, touchduration);
}
}
function touchend() {
//stops short touches from firing the event
if (timer) {
clearTimeout(timer);
timer = null;
}
}
onlongtouch = function() {
timer = null;
document.getElementById('ping').innerText+='ping\n';
};
document.addEventListener("DOMContentLoaded", function(event) {
window.addEventListener("touchstart", touchstart, false);
window.addEventListener("touchend", touchend, false);
});
<div id="ping"></div>
我已经在我的 Android 应用程序中这样做了:
注册事件监听器:
var touchStartTimeStamp = 0;
var touchEndTimeStamp = 0;
window.addEventListener('touchstart', onTouchStart,false);
window.addEventListener('touchend', onTouchEnd,false);
新增功能:
var timer;
function onTouchStart(e) {
touchStartTimeStamp = e.timeStamp;
}
function onTouchEnd(e) {
touchEndTimeStamp = e.timeStamp;
console.log(touchEndTimeStamp - touchStartTimeStamp);// in miliseconds
}
检查时差并完成我的工作
我希望这将有所帮助。
我们可以计算触摸开始和触摸结束的时间差。如果计算出的时间差超过触摸持续时间,则我们使用函数名称 taphold。
var touchduration = 300;
var timerInterval;
function timer(interval) {
interval--;
if (interval >= 0) {
timerInterval = setTimeout(function() {
timer(interval);
});
} else {
taphold();
}
}
function touchstart() {
timer(touchduration);
}
function touchend() {
clearTimeout(timerInterval);
}
function taphold(){
alert("taphold");
}
document.getElementById("xyz").addEventListener('touchstart',touchstart);
document.getElementById("xyz").addEventListener('touchend',touchend);
此处发布的解决方案忽略了用户需要触摸屏幕才能启动滚动的事实。如果用户不尝试滚动,我们只想要长按行为。
function onLongPress(element, callback) {
let timer;
element.addEventListener('touchstart', () => {
timer = setTimeout(() => {
timer = null;
callback();
}, 500);
});
function cancel() {
clearTimeout(timer);
}
element.addEventListener('touchend', cancel);
element.addEventListener('touchmove', cancel);
}
接着:
onLongPress(element, () => {
console.log('Long pressed', element);
});