2012-01-11 7 views
2

マウスボタンの状態(押されているか解放されているか)をチェックできます。私はこれがjqueryでのイベント処理の目的であることを知っていますが、マウスのボタンがボタンの位置の変更を必要とせずに押されていなければ機能を果たすことが可能かどうか疑問ですまたはその逆)?マウスボタンの位置を知るブール関数

+1

いいえ、これは実際にはあまり意味がありません。ブラウザは、そのようなモデルを公開していません。そのモデルは、常にすべてを監視しています。むしろ、世界の状態は、イベントが発生したときにキャプチャされ、登録されたハンドラに渡されます。さらに、キャプチャされたイベント情報は通常、イベントタイプに関連するものだけです。 – Pointy

+0

あなたは言い換えることができますか?私はこれを4回読んだが、まだそれを得ていない。 – karim79

+0

マウスボタンが押されたり離されたときだけでなく、マウスボタンの状態をいつでも理解できると思っていますか? – Jasper

答えて

3

は、あなたが変更されたマウスイベントを検出するmousedownmouseupイベントを使用することができ、ここで、コード、DEMOの下

$(document).mousedown (function() { 
    $('#result').text('Pressed'); 
}).mouseup (function() { 
    $('#result').text('Released'); 
}); 
1

を試してみてください。このイベントはwindowにバインドする必要があります。 デモ:、ブール値のコンテキストでは

0 Mouse released false 
1 Left click  true 
2 Middle click  true 
3 Right click  true 

マウスがダウンしていないときに、関数の戻り値の値がfalseと評価:http://jsfiddle.net/uwzbn/

var mouseState = (function(){ 
    var mousestatus = 0; 
    $(window).mousedown(function(e) { 
     mousestatus = e.which; 
    }).mouseup(function(e){ 
     mousestatus = 0; 
    }); 
    return function() { 
     return mousestatus; 
    } 
})(); 

この関数は、4つの値を返します。マウスを押すと、どのマウスキーが押されたか(ボーナスとして)を読むことができます。

+0

2つのボタンを押し下げて1つのボタンを押しても、自分のためにこれが賢明ではないかと思います。 :p – Esailija

+0

@Esailija現在のすべての回答がこの問題を抱えています。 Afaik、これには信頼できる解決策はありません。逆も可能です。コンテキストメニューを開き、メニュー内でマウスを放すことができます。マウスの状態は3で止まってしまうでしょう。 –

+0

もう少し複雑なコードではそれを克服することができますが(ブール値を追跡している場合はそれほど複雑ではありませんが)、contextmenuのことは克服できません。 – Esailija

1
$(function() { 

    //setup flag for the state of the mouse button and create an object that converts an event type into a boolean for the flag 
    var mousePressed = false, 
     mouseConvert = { 
      mousedown : true, 
      mouseup : false 
     }; 

    //bind to the document's mousedown and mouseup events to change the flag when necessary 
    $(document).on('mousedown mouseup', function (event) { 

     //set the flag to the new state of the mouse button 
     mousePressed = mouseConvert[event.type]; 

     //if you only want to watch one mouse button and not all of them then 
     //you can create an if/then statement here that checks event.which 
     //and only updates the flag if it is the button you want, check-out Rob W.'s 
     //answer to see the different values for event.which with respect to the mouse 
    }); 
    //now you can check the value of the `mousePressed` variable, if it is equal to `true` then the mouse is currently pressed 
}); 
関連する問題