JavaScript 中长按?
-
26-09-2019 - |
题
是否可以在 JavaScript(或 jQuery)中实现“长按”?如何?
(来源: androinica.com)
超文本标记语言
<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莫拉的回答,我写了这一点。这也确保用户没有做点击右键,将触发长按和作品在移动设备上。 演示
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; }
}
可以使用 taphold 强> jQuery的移动API的事件。
jQuery("a").on("taphold", function( event ) { ... } )
虽然它看起来确实很简单,可以通过超时和几个鼠标事件处理程序自行实现,但当您考虑单击-拖动-释放等情况时,它会变得有点复杂,支持在同一元素上同时按下和长按,以及使用 iPad 等触摸设备。我最终使用了 长按 jQuery 插件 (吉图布),它为我处理这些事情。如果您只需要支持手机等触摸屏设备,您也可以尝试 jQuery Mobile 轻按事件.
jQuery插件。只要把$(expression).longClick(function() { <your code here> });
。第二个参数是保持持续时间;默认超时是500毫秒。
(function($) {
$.fn.longClick = function(callback, timeout) {
var timer;
timeout = timeout || 500;
$(this).mousedown(function() {
timer = setTimeout(function() { callback(); }, timeout);
return false;
});
$(document).mouseup(function() {
clearTimeout(timer);
return false;
});
};
})(jQuery);
我创建长按压事件 (0.5K纯JavaScript)解决这个问题,它增加了一个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
强>元素:
// 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 +,浏览器,Firefox,Safari浏览器及混合移动应用程序(科尔多瓦&离子在iOS / Android的)
$(document).ready(function () {
var longpress = false;
$("button").on('click', function () {
(longpress) ? alert("Long Press") : alert("Short Press");
});
var startTime, endTime;
$("button").on('mousedown', function () {
startTime = new Date().getTime();
});
$("button").on('mouseup', function () {
endTime = new Date().getTime();
longpress = (endTime - startTime < 500) ? false : true;
});
});
对于跨平台开发的(注意:目前给出不会在iOS上工作的所有答案)
的MouseUp /下似乎工作在机器人好 - 但不是所有装置,即(三星TAB4)。没有在所有的工作在的iOS
进一步研究其似乎这是由于具有选择元件和天然放大率interupts监听器。
此事件侦听使微缩图像在自举模式被打开,如果用户握住宽度为500ms的图像。
它使用一因此响应图像类表示图像的放大版本。 这段代码已经在经过充分测试(ipad公司/ TAB4 /塔巴/ Galaxy4):
var pressTimer;
$(".thumbnail").on('touchend', function (e) {
clearTimeout(pressTimer);
}).on('touchstart', function (e) {
var target = $(e.currentTarget);
var imagePath = target.find('img').attr('src');
var title = target.find('.myCaption:visible').first().text();
$('#dds-modal-title').text(title);
$('#dds-modal-img').attr('src', imagePath);
// Set timeout
pressTimer = window.setTimeout(function () {
$('#dds-modal').modal('show');
}, 500)
});
在Diodeus的答案是真棒,但它阻止你添加的onClick功能,它永远不会运行保持功能,如果你把一个onclick。而拉扎克的回答几乎是完美的,但它只是在鼠标松开运行保持功能,一般的功能运行,即使用户继续保持。
因此,我加入两者,并且由这样的:
$(element).on('click', function () {
if(longpress) { // if detect hold, stop onclick function
return false;
};
});
$(element).on('mousedown', function () {
longpress = false; //longpress is false initially
pressTimer = window.setTimeout(function(){
// your code here
longpress = true; //if run hold function, longpress is true
},1000)
});
$(element).on('mouseup', function () {
clearTimeout(pressTimer); //clear time on mouseup
});
您可以设置用于在鼠标按下该元素的超时而清除它在鼠标弹起:
$("a").mousedown(function() {
// set timeout for this element
var timeout = window.setTimeout(function() { /* … */ }, 1234);
$(this).mouseup(function() {
// clear timeout for this element
window.clearTimeout(timeout);
// reset mouse up event handler
$(this).unbind("mouseup");
return false;
});
return false;
});
使用此每个元素都有自己的超时时间。
有关现代,移动浏览器:
document.addEventListener('contextmenu', callback);
您可以使用jQuery移动的taphold。包括jquery的-mobile.js和下面的代码将正常工作
$(document).on("pagecreate","#pagename",function(){
$("p").on("taphold",function(){
$(this).hide(); //your code
});
});
最优雅和清洁是一个jQuery插件: https://github.com/untill/jquery.longclick/ , 也可作为packacke: https://www.npmjs.com/package/jquery.longclick
在短,就用它像这样:
$( 'button').mayTriggerLongClicks().on( 'longClick', function() { your code here } );
这个插件的优点是,相对于这里的一些其他的答案中,单击事件仍然是可能的。还需要注意的是一个长按会出现,就像在设备上长按,鼠标松开之前。所以,这是一个特点。
有关我它的与该代码(用jQuery)工作:
var int = null,
fired = false;
var longclickFilm = function($t) {
$body.css('background', 'red');
},
clickFilm = function($t) {
$t = $t.clone(false, false);
var $to = $('footer > div:first');
$to.find('.empty').remove();
$t.appendTo($to);
},
touchStartFilm = function(event) {
event.preventDefault();
fired = false;
int = setTimeout(function($t) {
longclickFilm($t);
fired = true;
}, 2000, $(this)); // 2 sec for long click ?
return false;
},
touchEndFilm = function(event) {
event.preventDefault();
clearTimeout(int);
if (fired) return false;
else clickFilm($(this));
return false;
};
$('ul#thelist .thumbBox')
.live('mousedown touchstart', touchStartFilm)
.live('mouseup touchend touchcancel', touchEndFilm);
您可以检查以确定时间点击或长按[jQuery的]
function AddButtonEventListener() {
try {
var mousedowntime;
var presstime;
$("button[id$='" + buttonID + "']").mousedown(function() {
var d = new Date();
mousedowntime = d.getTime();
});
$("button[id$='" + buttonID + "']").mouseup(function() {
var d = new Date();
presstime = d.getTime() - mousedowntime;
if (presstime > 999/*You can decide the time*/) {
//Do_Action_Long_Press_Event();
}
else {
//Do_Action_Click_Event();
}
});
}
catch (err) {
alert(err.message);
}
}
这样?
doc.addEeventListener("touchstart", function(){
// your code ...
}, false);
您可以使用jquery
触摸事件。 (见这里)
let holdBtn = $('#holdBtn')
let holdDuration = 1000
let holdTimer
holdBtn.on('touchend', function () {
// finish hold
});
holdBtn.on('touchstart', function () {
// start hold
holdTimer = setTimeout(function() {
//action after certain time of hold
}, holdDuration );
});
我需要的东西,长按键盘事件,所以我写了这一点。
var longpressKeys = [13];
var longpressTimeout = 1500;
var longpressActive = false;
var longpressFunc = null;
document.addEventListener('keydown', function(e) {
if (longpressFunc == null && longpressKeys.indexOf(e.keyCode) > -1) {
longpressFunc = setTimeout(function() {
console.log('longpress triggered');
longpressActive = true;
}, longpressTimeout);
// any key not defined as a longpress
} else if (longpressKeys.indexOf(e.keyCode) == -1) {
console.log('shortpress triggered');
}
});
document.addEventListener('keyup', function(e) {
clearTimeout(longpressFunc);
longpressFunc = null;
// longpress key triggered as a shortpress
if (!longpressActive && longpressKeys.indexOf(e.keyCode) > -1) {
console.log('shortpress triggered');
}
longpressActive = false;
});