长期在JavaScript?

Ran*_*yer 111 javascript jquery jquery-ui jquery-mobile jquery-events

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

alt text http://androinica.com/wp-content/uploads/2009/11/longpress_options.png

HTML

<a href="" title="">Long press</a>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

$("a").mouseup(function(){
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  return false; 
});
Run Code Online (Sandbox Code Playgroud)

Dio*_*ane 158

没有'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; 
});
Run Code Online (Sandbox Code Playgroud)

  • 这也不会在阻力上发生火灾吗? (36认同)
  • @Gallal据说通过在`mousemove`上调用`clearTimeout(pressTimer)`可以相当简单,除非我遗漏了什么.诚然,这几乎不可能是前所未有的. (11认同)
  • 请记住,如果您希望这可以在手机上运行,​​它们通常会有自己的默认长按行为(例如,在Android上显示一个模式菜单,当您长按链接时会显示各种选项).我没有很多运气阻止这一点,说实话,干扰浏览器默认行为无论如何都是隐藏的. (6认同)
  • 尽管这是选定的答案,但它并没有真正回答问题。它过于简单化和天真。任何长按事件都必须解决此答案忽略的多个问题。1) 区分长按与多点触控手势拖动(即捏放大或缩小) 2) 如果移动到元素或浏览器区域之外则取消 3) 解决大量平台和设备上文本选择的默认行为 4) 允许一个可配置的灵敏度阈值,不依赖于幻数。对于可访问性问题特别有帮助,但并非仅限于此。 (5认同)
  • @DavidJohnWelsh正是我一直在看的东西,你不只是想让鼠标移动 - 让你的手指稳定而且不动1px是相当困难的!你需要应用一个阈值(如果鼠标没有移动10px)等等.很快就复杂了! (4认同)
  • 另外......你需要指定$("a").click(function(){return false;}); (2认同)

kel*_*nik 30

根据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);
Run Code Online (Sandbox Code Playgroud)

您还应该使用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; }
}
Run Code Online (Sandbox Code Playgroud)


dog*_*nak 25

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

jQuery("a").on("taphold", function( event ) { ... } )
Run Code Online (Sandbox Code Playgroud)

  • 请注意:jquery mobile与jquery ui冲突.另见http://stackoverflow.com/questions/24379514/how-to-resolve-the-conflict-between-jquery-ui-and-jquery-mobile (2认同)

ʇsә*_*ɹoɈ 15

虽然它看起来很简单,可以通过超时和几个鼠标事件处理程序自行实现,但是当您考虑点击 - 拖动 - 释放等情况时,它会变得有点复杂,同时支持按下和长按相同的元素,以及使用iPad等触控设备.我最终使用了longclick jQuery插件(Github),它为我处理这些东西.如果您只需要支持移动电话等触摸屏设备,您也可以尝试jQuery Mobile taphold活动.


Joh*_*rty 12

我创建了长按事件 (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);
});
Run Code Online (Sandbox Code Playgroud)

侦听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);
});
Run Code Online (Sandbox Code Playgroud)

适用于IE9 +,Chrome,Firefox,Safari和混合移动应用程序(iOS/Android上的Cordova和Ionic)

演示

  • 它是开源的,随时为该项目做出贡献:) (3认同)
  • 只要在“long-press-delay”计时器启动之前释放长按,您仍然应该获得“onclick”事件 (3认同)
  • 太棒了,伙计!! (2认同)
  • 这个解决方案猴子以一种有点随意、不完整和非标准的方式修补 window.CustomEvent 对象。它没有正确地将只读属性创建为只读而是读写。它特别缺少 returnValue、type、timeStamp 和 isTrusted。它没有解决拖动、手势、双指放大或缩小或长按的多点触控失火问题,也没有解决大量设备和/或平台的问题,这些设备和/或平台即使在 500 毫秒时也默认长按进行文本选择。该库缺少这些条件的任何和所有测试用例。 (2认同)

小智 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);
Run Code Online (Sandbox Code Playgroud)


小智 10

对于现代移动浏览器:

document.addEventListener('contextmenu', callback);
Run Code Online (Sandbox Code Playgroud)

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

  • 停止使用 `bind()` jquery 1.7+ = `on()` 和 `unbind()` = `off()` (2认同)

tyl*_*ell 6

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

Mouseup / down似乎在android上可以正常工作-但并非所有设备(例如,三星tab4)。在iOS上根本无法使用。

进一步的研究似乎认为这是由于元素具有选择能力以及自然放大率干扰了听众。

如果用户按住该图像500毫秒,则此事件侦听器将以引导方式打开该缩略图。

它使用了响应式图像类,因此显示了较大版本的图像。此代码段已在(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)
});
Run Code Online (Sandbox Code Playgroud)


raz*_*zak 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;
    });
});
Run Code Online (Sandbox Code Playgroud)

DEMO

  • 使用此代码,在500ms结束时不会触发longclick.用户可以点击鼠标:).仅当用户停止单击按钮时才会触发长按. (2认同)