Frage

Ist es möglich, "long press" in JavaScript zu implementieren (oder jQuery)? Wie?


(Quelle: androinica.com )

HTML

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

JavaScript

$("a").mouseup(function(){
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  return false; 
});
War es hilfreich?

Lösung

Es gibt keine magische 'jQuery', nur JavaScript-Timer.

var pressTimer;

$("a").mouseup(function(){
  clearTimeout(pressTimer);
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() { ... Your Code ...},1000);
  return false; 
});

Andere Tipps

Basierend auf Maycow Moura Antwort schrieb ich dies. Es stellt auch sicher, dass der Benutzer nicht einen Rechtsklick machen, das eine lange Presse und Arbeiten auf mobilen Geräten auslösen würde. 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);

Sie sollten auch einigen Indikator mit CSS-Animationen enthalten:

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

Sie können mit taphold Ereignis von jQuery Mobile API.

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

Während es Blick einfach genug tut auf eigene Faust mit einem Timeout zu implementieren und ein paar Maus-Event-Handler, wird es ein wenig komplizierter, wenn man Fälle wie Click-Drag-Release berücksichtigen, sowohl Presse unterstützt und lang drückt auf das gleiche Element, und die Arbeit mit Touch-Geräte wie das iPad. Ich landete mit dem longclick jQuery-Plugin ( Github ), die Pflege für mich das Zeug nimmt. Wenn Sie nur wie Mobiltelefone Unterstützung Touchscreen-Geräte benötigen, können Sie auch versuchen, das jQuery Mobile taphold Ereignis .

jQuery-Plugin. Setzen Sie einfach $(expression).longClick(function() { <your code here> });. Zweiter Parameter ist Haltedauer; Standard-Timeout 500 ms.

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

Ich habe Langpress Veranstaltung (0.5k reine JavaScript) , diese zu lösen, es fügt ein long-press Ereignis in das DOM.

Hören für eine long-press auf jeder Elemente:

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

Hören für eine long-press auf spezifisches Element:

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

Arbeiten in IE9 +, Chrome, Firefox, Safari & hybrid mobile Anwendungen (Cordova & Ionic auf iOS / Android)

Demo

$(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

Für Cross-Plattform-Entwickler (Hinweis: Alle bisher gegebenen Antworten wird nicht auf iOS) :

mouseup / unten schien Arbeit in Ordnung auf Android - aber nicht alle Geräte, dh (Samsung TAB4). Hat nicht funktioniert überhaupt auf iOS .

Weitere Forschung seines scheint, dass dies das Element Auswahl beruht und die nativen Vergrößerung interupts der Hörer.

Dieser Ereignis-Listener ermöglicht ein Thumbnail-Bild in einem Bootstrap-modal geöffnet werden, wenn der Benutzer das Bild für 500ms hält.

Es verwendet eine ansprechende Bildklasse daher eine größere Version des Bildes zeigt. Dieses Stück Code wurde vollständig getestet auf (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)
});

Die Antwort des Diodeus ist genial, aber es verhindert, dass Sie eine onClick Funktion hinzuzufügen, wird es nie Hold-Funktion ausführen, wenn Sie ein Onclick setzen. Und die Razzak Antwort ist fast perfekt, aber es läuft Hold-Funktion nur auf mouseup und allgemein die Funktion läuft, auch wenn Benutzer Keep Holding.

So trat ich beide, und machte diese:

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

Sie können das Timeout für dieses Element auf Maus-Set nach unten und deaktivieren Sie es auf Maus nach oben:

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

Mit dieser jedes Element erhält eine eigene Timeout.

Für die modernen, mobilen Browser:

document.addEventListener('contextmenu', callback);

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

Sie können jQuery-Mobile taphold verwenden. Fügen Sie die Jquery-mobile.js und der folgende Code wird funktionieren

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

Die meisten elegant und sauber ist eine jQuery-Plugin: https://github.com/untill/jquery.longclick/ , auch als packacke: https://www.npmjs.com/package/jquery.longclick .

Kurz gesagt, verwenden Sie es mögen so:

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

Der Vorteil dieses Plugin ist, dass im Gegensatz zu einigen der anderen Antworten hier klicken Ereignisse nach wie vor möglich sind. Beachten Sie auch, dass ein langer Klick auf, wie ein langes Tippen auf einem Gerät, bevor mouseup. Also, das ist ein Feature.

Für mich ist es die Arbeit mit diesem Code (mit 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);

Sie können die Zeit überprüfen, um zu identifizieren Klicken oder Lang Drücken Sie [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);
}
} 

so?

doc.addEeventListener("touchstart", function(){
    // your code ...
}, false);    

Sie können jquery Touch-Ereignisse verwenden. ( sehen hier )

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

brauchte ich etwas für Longpress Tastatur-Ereignisse, so dass ich dieses geschrieben habe.

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;
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top