この状況に関連するスタックオーバーフローに関するいくつかの回答を読みましたが、解決策はどれも機能していません。
ユーザーが要素をクリックするか、jQueryを使用してその要素をマウスで押したままにするかに基づいて、さまざまなことをしようとしています。
これを達成することは可能ですか?
この状況に関連するスタックオーバーフローに関するいくつかの回答を読みましたが、解決策はどれも機能していません。
ユーザーが要素をクリックするか、jQueryを使用してその要素をマウスで押したままにするかに基づいて、さまざまなことをしようとしています。
これを達成することは可能ですか?
onMouseDown は、左または右 (または中央) が押されたときにトリガーされます。同様に、onMouseUp は、いずれかのボタンが離されたときにトリガーされます。onMouseDown は、マウスがオブジェクトをクリックしてから離した場合でもトリガーされますが、onMouseUp は、ボタンをクリックして別の場所で押したままにし、オブジェクトの上で離すとトリガーされます。
onClick は、同じオブジェクト上でマウスの左ボタンを押して離したときにのみトリガーされます。順序が気になる場合は、同じオブジェクトに 3 つのイベントがすべて設定されている場合、onMouseDown、onMouseUp、onClick の順になります。ただし、各イベントは一度だけトリガーする必要があります。
詳細:
クリックとホールドの両方をサポートするソリューションは次のとおりです。
// Timeout, started on mousedown, triggers the beginning of a hold
var holdStarter = null;
// Milliseconds to wait before recognizing a hold
var holdDelay = 500;
// Indicates the user is currently holding the mouse down
var holdActive = false;
// MouseDown
function onMouseDown(){
// Do not take any immediate action - just set the holdStarter
// to wait for the predetermined delay, and then begin a hold
holdStarter = setTimeout(function() {
holdStarter = null;
holdActive = true;
// begin hold-only operation here, if desired
}, holdDelay);
}
// MouseUp
function onMouseUp(){
// If the mouse is released immediately (i.e., a click), before the
// holdStarter runs, then cancel the holdStarter and do the click
if (holdStarter) {
clearTimeout(holdStarter);
// run click-only operation here
}
// Otherwise, if the mouse was being held, end the hold
else if (holdActive) {
holdActive = false;
// end hold-only operation here, if desired
}
}
// Optional add-on: if mouse moves out, then release hold
function onMouseOut(){
onMouseUp();
}
ここにデモがあります:http://jsfiddle.net/M7hT8/1/
もともと daveyfaherty のソリューションに基づいています。この質問は少し前のものであることは知っていますが、検索でこれを見つけた人のために私の解決策を共有しています.
//last mouse coordinate
var mouseX = 0;
//epsilon interval
var mouseEps = 10;
function mouseDownHandler(e) {
e.preventDefault();
mouseX = e.clientX;
};
function mouseUpHandler(e) {
e.preventDefault();
if (Math.abs((mouseX - e.clientX)) < mouseEps) {
clickHandler(e);
}
};
function clickHandler(e) {
};