长按JavaScript?

是否有可能实现JavaScript(或jQuery)的“长按”? 怎么样?

替代文字http://androinica.com/wp-content/uploads/2009/11/longpress_options.png

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; }); 

您可以使用jQuery移动API的taphold事件。

基于Maycow Moura的回答,我写了这个。 这也确保了用户没有做出正确的点击,这将触发长时间的按压并在移动设备上工作。 DEMO

 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); 

你还应该使用CSSanimation包含一些指标:

 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; } } 

虽然它看起来很简单,可以自己实现一个超时和一些鼠标事件处理程序,但是当您考虑像点击拖动释放这样的情况时,它会变得更加复杂一些,同时支持按和长按,并与iPad等触摸设备一起工作。 我最终使用了longclick jQuery插件 ( Github ),它为我处理这些东西。 如果您只需要支持手机等触摸屏设备,则还可以尝试jQuery Mobile taphold事件 。

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); 
 $(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; }); }); 

DEMO

对于跨平台开发人员(注意到目前为止所有的答案都不适用于iOS)

鼠标/下来似乎在Android上工作正常 – 但不是所有的设备即(三星tab4)。 在iOS上完全没有工作。

进一步的研究似乎认为,这是由于元素有select性,而原生的放大效应干扰了聆听者。

如果用户将图像保持500ms,则此事件侦听器将使缩略图图像以引导模式打开。

它使用响应式图像类,因此显示图像的更大版本。 这段代码已经完全testing(iPad / Tab4 / TabA / 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,它永远不会运行保持函数。 Razzak的答案几乎是完美的,但是它只对mouseup运行保持function,并且一般来说,即使用户保持不动,该function也会运行。

所以,我join了两个,并做了这个:

 $(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; }); 

这个每个元素都有自己的超时。

你可以使用jquery-mobile的taphold。 包括jquery-mobile.js和下面的代码将正常工作

 $(document).on("pagecreate","#pagename",function(){ $("p").on("taphold",function(){ $(this).hide(); //your code }); }); 

对于现代的移动浏览器:

 document.addEventListener('contextmenu', callback); 

https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu

最优雅和干净的是一个jQuery插件: https : //github.com/untill/jquery.longclick/ ,也可作为packacke: https ://www.npmjs.com/package/jquery.longclick。

总之,你这样使用它:

 $( 'button').mayTriggerLongClicks().on( 'longClick', function() { your code here } ); 

这个插件的优点是,与其他一些答案相比,点击事件仍然是可能的。 还要注意,长时间点击发生,就像一个设备上的长按,在mouseup之前。 所以,这是一个function。

使用长按 ,它为所有元素增加了一个long-press事件。

long-press任何 HTML元素:

 // the event bubbles, so you can listen at the root level document.addEventListener('long-press', function(e) { console.log(e.target); }); 

long-press 特定的 HTML元素:

 // 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 – 包括Cordova,Phone Gap,Ionic混合移动应用程序。

对我来说,它是与该代码(与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);