长期在JavaScript?

问题描述 投票:108回答:18

是否可以在JavaScript(或jQuery)中实现“长按”?怎么样?

alt text (来源: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 jquery-ui jquery-mobile javascript-events
18个回答
155
投票

没有'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; 
});

2
投票

您可以在鼠标按下时设置该元素的超时并在鼠标向上清除它:

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

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


2
投票

对于现代移动浏览器:

document.addEventListener('contextmenu', callback);

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


1
投票

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

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

1
投票

最优雅和干净的是一个jQuery插件:qazxsw poi,也可以作为包:qazxsw poi。

简而言之,您可以像这样使用它:

https://github.com/untill/jquery.longclick/

这个插件的优点是,与此处的其他一些答案相比,单击事件仍然是可能的。另请注意,在鼠标放置之前,就像在设备上长按一样,会发生长时间点击。所以,这是一个功能。


0
投票

对我来说,它可以使用该代码(使用jQuery):

https://www.npmjs.com/package/jquery.longclick

0
投票

您可以检查识别点击或长按的时间[jQuery]

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

0
投票

像这样?

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

0
投票

您可以使用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); } } Touch活动。 (doc.addEeventListener("touchstart", function(){ // your code ... }, false);

jquery

0
投票

我需要长按键盘事件的东西,所以我写了这个。

see here

29
投票

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

您还应该使用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; }
}

25
投票

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

jQuery("a").on("taphold", function( event ) { ... } )

15
投票

虽然它看起来很简单,可以通过超时和几个鼠标事件处理程序自行实现,但是当您考虑点击 - 拖动 - 释放,同时支持按下和长按同一元素时,它会变得有点复杂,以及使用iPad等触控设备。我最终使用了longclick jQuery pluginGithub),它为我照顾那些东西。如果您只需要支持手机等触摸屏设备,您也可以试试jQuery Mobile taphold event


10
投票

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

9
投票

我创建了long-press-event(0.5k纯JavaScript)来解决这个问题,它向DOM添加了一个long-press事件。

在任何元素上听取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 +,Chrome,Firefox,Safari和混合移动应用程序(iOS / Android上的Cordova和Ionic)

Demo


5
投票
$(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


5
投票

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

Mouseup / down似乎在android上运行正常 - 但不是所有设备(三星标签4)。在iOS上根本没用。

进一步研究它似乎是由于元素具有选择和原生放大率中断听众。

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

它使用响应式图像类,因此显示更大版本的图像。这段代码已经过全面测试(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)
});

4
投票

Diodeus的答案很棒,但它阻止你添加一个onClick函数,如果你放一个onclick它就永远不会运行hold函数。 Razzak的答案几乎是完美的,但它只在mouseup上运行hold函数,一般来说,即使用户继续保持,该函数也会运行。

所以,我加入了两个,并做了这个:

$(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
});
© www.soinside.com 2019 - 2024. All rights reserved.