是否可以在 JavaScript(或 jQuery)中实现“长按”?如何?
(来源:androinica.com)
HTML
<a href="" title="">Long press</a>
JavaScript
$("a").mouseup(function(){
// Clear timeout
return false;
}).mousedown(function(){
// Set timeout
return false;
});
是否可以在 JavaScript(或 jQuery)中实现“长按”?如何?
(来源:androinica.com)
HTML
<a href="" title="">Long press</a>
JavaScript
$("a").mouseup(function(){
// Clear timeout
return false;
}).mousedown(function(){
// Set timeout
return false;
});
没有“jQuery”魔法,只有 JavaScript 计时器。
var pressTimer;
$("a").mouseup(function(){
clearTimeout(pressTimer);
// Clear timeout
return false;
}).mousedown(function(){
// Set timeout
pressTimer = window.setTimeout(function() { ... Your Code ...},1000);
return false;
});
根据 Maycow Moura 的回答,我写了这个。它还确保用户没有执行右键单击,这会触发长按并在移动设备上工作。演示
var node = document.getElementsByTagName("p")[0];
var longpress = false;
var presstimer = null;
var longtarget = null;
var cancel = function(e) {
if (presstimer !== null) {
clearTimeout(presstimer);
presstimer = null;
}
this.classList.remove("longpress");
};
var click = function(e) {
if (presstimer !== null) {
clearTimeout(presstimer);
presstimer = null;
}
this.classList.remove("longpress");
if (longpress) {
return false;
}
alert("press");
};
var start = function(e) {
console.log(e);
if (e.type === "click" && e.button !== 0) {
return;
}
longpress = false;
this.classList.add("longpress");
if (presstimer === null) {
presstimer = setTimeout(function() {
alert("long click");
longpress = true;
}, 1000);
}
return false;
};
node.addEventListener("mousedown", start);
node.addEventListener("touchstart", start);
node.addEventListener("click", click);
node.addEventListener("mouseout", cancel);
node.addEventListener("touchend", cancel);
node.addEventListener("touchleave", cancel);
node.addEventListener("touchcancel", cancel);
您还应该使用 CSS 动画包含一些指标:
p {
background: red;
padding: 100px;
}
.longpress {
-webkit-animation: 1s longpress;
animation: 1s longpress;
}
@-webkit-keyframes longpress {
0%, 20% { background: red; }
100% { background: yellow; }
}
@keyframes longpress {
0%, 20% { background: red; }
100% { background: yellow; }
}
您可以使用jQuery 移动 API 的taphold事件。
jQuery("a").on("taphold", function( event ) { ... } )
我创建了long-press-event (0.5k pure JS)来解决这个问题,它long-press
向 DOM添加了一个事件。
侦听long-press
上的任何元素:
// the event bubbles, so you can listen at the root level
document.addEventListener('long-press', function(e) {
console.log(e.target);
});
侦听特定元素long-press
上的 a :
// get the element
var el = document.getElementById('idOfElement');
// add a long-press event listener
el.addEventListener('long-press', function(e) {
// stop the event from bubbling up
e.preventDefault()
console.log(e.target);
});
适用于 IE9+、Chrome、Firefox、Safari 和混合移动应用程序(iOS/Android 上的 Cordova 和 Ionic)
虽然它看起来很简单,可以通过超时和几个鼠标事件处理程序自行实现,但当您考虑单击-拖动-释放等情况时,它会变得有点复杂,在同一元素上同时支持按下和长按,并使用 iPad 等触控设备。我最终使用了longclick jQuery 插件( Github ),它为我处理这些事情。如果你只需要支持手机等触屏设备,你也可以试试jQuery Mobile的taphold事件。