簡體   English   中英

jQuery中的鼠標按下事件

[英]Mouse press event in jQuery

我需要檢測jQuery中的鼠標按下事件。 我看到了這個問題它就是答案 這正是我需要的,因為只有在按下和移動鼠標的情況下,操作才會發生。 這不是單擊事件,而是鼠標按下和移動事件的組合。

我不知道如何實現它。 當前,我使用以下代碼旋轉div,但是此代碼基於mousedown事件:

 var rotation = 0; jQuery.fn.rotate = function(degrees) { $(this).css({'transform' : 'rotate('+ degrees +'deg)'}); }; $('.resizeButton').on("mousedown", function(e) { var startX = e.pageX; $(document).mousemove(function(e){ rotation = startX - e.pageX; $('.test').rotate(rotation); }); }); $('.resizeButton').on("mouseup", function(){ $(document).unbind( "mousemove" ); }); 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test">Hello <button class="resizeButton"> </button> </div> 

請幫助將其轉換為鼠標按下和移動事件 ,以便用戶可以輕松地通過按下該按鈕並向任意方向旋轉並釋放鼠標來調整旋轉。 當用戶釋放鼠標按下時,然后需要在該特定的鼠標按下釋放點上設置旋轉。

您的代碼中存在一些問題。

首先,“ mouseup”事件處理程序不會被觸發,因為釋放鼠標時,鼠標不在復選框上方。 例如,您必須將事件綁定到文檔。

然后,與其綁定和取消綁定事件處理程序,不如存儲鼠標狀態並僅在按下鼠標時旋轉,可能更容易。

 var rotation = 0; var rotating = false; var startX = 0; jQuery.fn.rotate = function(degrees) { $(this).css({'transform' : 'rotate('+ degrees +'deg)'}); }; $(document).mousemove(function(e){ if (!rotating) return; rotation = startX - e.clientX; $('.test').rotate(rotation); }); $(document).on("mouseup", function(){ rotating = false; }); $('.resizeButton').on("mousedown", function(e) { rotating = true; startX = e.clientX; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test">Hello <button class="resizeButton"> </button></div> 

要使按鈕在旋轉過程中跟隨鼠標指針,可能需要使用一些sin和cos函數來確定旋轉角度,並且可能還需要調整半徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM