长按JavaScript?

长按JavaScript?,javascript,jquery,jquery-ui,jquery-mobile,jquery-events,Javascript,Jquery,Jquery Ui,Jquery Mobile,Jquery Events,是否可以在JavaScript(或jQuery)中实现“长按”?怎么做 (来源:) HTML <a href="" title="">Long press</a> 没有“jQuery”魔力,只有JavaScript计时器 var pressTimer; $("a").mouseup(function(){ clearTimeout(pressTimer); // Clear timeout return false; }).mousedown(funct

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


(来源:)

HTML

<a href="" title="">Long press</a>

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

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

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

<> p>这个元素每一个元素都有自己的超时。

虽然它看起来很简单,可以用一个超时和几个鼠标事件处理程序自己实现,但是当你考虑点击拖动释放的情况时,它会变得更复杂,支持在同一个元素上同时按下和长按,以及使用iPad等触摸设备。我最终使用了()来处理这些东西。如果您只需要支持手机等触摸屏设备,您也可以尝试使用jQuery mobile API的事件

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

对我来说,这是使用该代码(使用jQuery)的工作:


您可以检查确定单击或长按[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);
}
} 

jQuery插件。只需放入
$(表达式).longClick(函数(){})。第二个参数是保持持续时间;默认超时为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);
$(文档).ready(函数(){
var longpress=false;
$(“按钮”)。在('click',函数(){
(长按)?警报(“长按”):警报(“短按”);
});
var startTime,endTime;
$(“按钮”)。在('mousedown',函数(){
startTime=新日期().getTime();
});
$(“按钮”)。在('mouseup',函数(){
endTime=newdate().getTime();
longpress=(endTime-startTime<500)?false:true;
});
});

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

根据Maycow Moura的回答,我写了这个。它还确保了用户没有右键点击,这将触发长按并在移动设备上工作

您还应该包括一些使用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 mobile的taphold。包括jquery-mobile.js,下面的代码就可以了

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

对于现代移动浏览器:

document.addEventListener('contextmenu', callback);

最优雅、最干净的是jQuery插件: , 也可通过Package获得:

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

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

这个插件的优点是,与这里的一些其他答案相比,点击事件仍然是可能的。还请注意,长时间的点击会在鼠标按下之前发生,就像长时间点击设备一样。因此,这是一个特性。

对于跨平台开发人员(注意,目前给出的所有答案在iOS上都不起作用)

Mouseup/down在安卓系统上似乎可以正常工作,但并非所有设备都可以使用ie(三星tab4)。在iOS上根本不工作

进一步的研究表明,这似乎是由于元素具有选择性,而本机放大会干扰听者

此事件侦听器允许在引导模式下打开缩略图图像(如果用户持有该图像500毫秒)

它使用响应图像类,因此显示图像的更大版本。 这段代码已经在(iPad/Tab4/TabA/Galaxy4)上进行了全面测试:

像这样

target.addEeventListener("touchstart", function(){
   // your code ...
}, false);    
我创建了(0.5k纯JS)来解决这个问题,它向DOM添加了一个
长按事件

任何元素上收听
长按

// the event bubbles, so you can listen at the root level
document.addEventListener('long-press', function(e) {
  console.log(e.target);
});
// 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);
});
特定元素上收听
长按

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


您可以使用
jquery
触摸事件。()


我需要一些关于longpress键盘事件的东西,所以我写了这个

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;
});
这对我很有用:

const a = document.querySelector('a');

a.oncontextmenu = function() {
   console.log('south north');
};

我可能会使用您的代码作为基础创建自定义jQuery事件,这样您就可以执行
jQuery(…).longclick(function(){…})问题没有用jQuery标记,尽管它应该被标记。这个问题首先询问一个纯Javascript解决方案,我更喜欢它,或者(在括号中)一个jQuery解决方案。大多数答案似乎默认使用jQuery作为标准假设。我一直鄙视jQuery,从未使用过它,也从未觉得有任何迫切的需要。有些人喜欢使用它,这是很好的,每个人自己。使用任何一种技术的答案都不会造成任何伤害。但是由于这个问题将接受jQuery解决方案,jQuery标签可能会吸引更多眼球,并有望得到更好的答案。这里的jQuery答案似乎很平淡。
$(this).mouseup(function(){})
不会删除事件处理程序,而是添加另一个事件处理程序。使用
.unbind
代替。现在应该使用
off()
而不是unbind。这不会也是一个拖拉触发吗?@Gallal通过调用
clearTimeout(pressTimer)
on
mousemove
,除非我遗漏了什么。诚然,这并不是没有先例的。@DavidJohnWelsh正是我所看到的,你不只是想让鼠标移动——让你的手指保持静止,不移动1px是相当困难的!你们需要应用一个阈值(若鼠标并没有移动10px)等等。很快就会变得复杂起来!请记住,如果你希望这在手机上起作用,它们通常有自己的默认longpress行为(例如,android上的chrome在你长按链接时会显示一个带有各种选项的模式菜单)。我没有太多的运气阻止这一点,老实说,干扰浏览器默认行为是一种无中生有的行为。虽然这是选择的答案,但它并不是真正的回答问题。它过于简单和天真。任何长时间的新闻发布会都必须解决这个答案忽略的多个问题。1) 区分长按、拖动、手势和多点触摸(i
// 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);
});
  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;
});
const a = document.querySelector('a');

a.oncontextmenu = function() {
   console.log('south north');
};