JavaScriptで長押し?
-
26-09-2019 - |
質問
JavaScript(またはjQuery)で「長押し」を実装することはできますか?どうやって?
(ソース: アンドロニカ.com)
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;
});
他のヒント
Maycow Moura の回答に基づいて、これを書きました。また、ユーザーが右クリックを行っていないことも保証されます。右クリックすると長押しがトリガーされ、モバイル デバイスでも機能します。 デモ
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; }
}
使用できます タップホールド jQueryモバイルAPIのイベント。
jQuery("a").on("taphold", function( event ) { ... } )
タイムアウトといくつかのマウス イベント ハンドラーを使用して独自に実装するのは十分簡単に見えますが、クリック、ドラッグ、リリースなどのケースを考慮すると、同じ要素のプレスと長押しの両方をサポートすることを考慮すると、少し複雑になります。 、iPad などのタッチ デバイスでの作業も可能です。結局使ったのは、 ロングクリック jQuery プラグイン (ギットハブ)、それは私に代わって処理します。携帯電話などのタッチスクリーン デバイスのみをサポートする必要がある場合は、次の方法も試してください。 jQueryモバイルのタップホールドイベント.
jQueryプラグイン。置くだけ $(expression).longClick(function() { <your code here> });
. 。2 番目のパラメータはホールド期間です。デフォルトのタイムアウトは 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);
わたしは作った 長押しイベント (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);
});
ちょっと聞いてください 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) で動作します。
$(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;
});
});
クロスプラットフォーム開発者向け (これまでに提供されたすべての回答は iOS では機能しないことに注意してください):
マウスのアップ/ダウンは問題なく動作しているようでした アンドロイド - ただし、すべてのデバイス (samsung 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)
});
Dideus の答えは素晴らしいですが、onClick 関数を追加することはできません。onclick を置いた場合、hold 関数は決して実行されません。そして、Razzakの答えはほぼ完璧ですが、ホールド機能はマウスアップ時にのみ実行され、一般に、ユーザーが押し続けた場合でも機能は実行されます。
そこで、両方を結合してこれを作成しました。
$(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;
});
これにより、各要素は独自のタイムアウトを取得します。
最新のモバイル ブラウザの場合:
document.addEventListener('contextmenu', callback);
https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu
jquery-mobileのタップホールドを利用することができます。jquery-mobile.js を含めると、次のコードは正常に動作します。
$(document).on("pagecreate","#pagename",function(){
$("p").on("taphold",function(){
$(this).hide(); //your code
});
});
最もエレガントでクリーンなのは、jQuery プラグインです。https://github.com/untill/jquery.longclick/, Packackeとしても入手可能:https://www.npmjs.com/package/jquery.longclick.
要するに、次のように使用します。
$( 'button').mayTriggerLongClicks().on( 'longClick', function() { your code here } );
このプラグインの利点は、ここでの他の回答の一部とは対照的に、クリック イベントが依然として可能であることです。また、デバイスを長押しするのと同じように、マウスアップの前に長押しのクリックが発生することにも注意してください。それで、それが特徴です。
私にとって、それはそのコード(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);
使用できます jquery
タッチイベント。(ここを参照してください)
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;
});