2017-03-01 54 views
1

所以我有一個拖動元素的web應用程序(在html,css和javascript,jquery中)(這意味着,由於元素隨着光標移動,光標不會移動該元素)。我希望將光標更改爲「移動」光標,但我遇到了這種奇怪的行爲。我寫了這段代碼來演示:在不移動光標時更改

<html> 
<head></head> 
<body oncontextmenu="return false;"> 
    <script> 
     var b=document.getElementsByTagName('body')[0]; 
     b.onmousedown=function(event){ 
      if(event.button){ 
       b.style.cursor='move'; 
      } 
     } 
     b.onmouseup=function(event){ 
      if(event.button){ 
       b.style.cursor='initial'; 
      }    
     } 
    </script> 
</body> 
</html> 

所以基本上,我想讓光標變成'光標:移動'每當用戶按住鼠標右鍵時,但是,會發生以下情況:

  • 初始:光標:默認
  • 按下鼠標:光標:默認
  • 鼠標移動:光標:默認
  • 鼠標向上:光標:移動
  • 鼠標移動:光標:默認

所以現在我的問題是:爲什麼會發生這種情況,以及如何解決這個問題?

PS:鉻測試,這是主要的瀏覽器,我需要這

回答

1

http://jsbin.com/vepihik/edit?html,css,js,output

document.addEventListener('mousedown', onMouseAction) 
 
document.addEventListener('mouseup', onMouseAction) 
 

 
function onMouseAction(e){ 
 
    document.body.style.cursor = e.buttons && e.button == 2 ? 'move' : 'default';   
 
}
html, body{ height:100%; }
Try to hold the RIGHT mouse button and move it, then release

工作附加文檔上的mousedownmouseup事件本身,並使他們都調用相同的功能,只需檢查點擊按鈕。 right = 2你的情況。

+0

這似乎並不鼠標按鈕被釋放時,將光標重置爲默認樣式。 'e.button == 2'將永遠是這種情況,因爲它是相同的按鈕。它需要通過事件_type_區分。 – CBroe

+0

由於打開了上下文菜單,它只是變回默認光標。如果你添加'oncontextmenu =「返回false;」'到'body'你的代碼片段不再工作 – vrugtehagel

+0

@vrugtehagel - opps對不起,我編輯它,它搞砸了。我會再次編輯! – vsync

1

您可以附加mousedownmouseup事件來啓動將更改和還原光標的函數。

在每個功能中,您可以確認剛按下(或釋放)的按鈕是鼠標右鍵。

工作實例:

var div = document.getElementsByTagName('div')[0]; 
 

 
function changeCursorToMove(event) { 
 
\t if ((event.which === 3) || (event.button === 2)) { 
 
     div.classList.add('move-cursor'); 
 
    } 
 
} 
 

 
function changeCursorToDefault(event) { 
 
\t if ((event.which === 3) || (event.button === 2)) { 
 
     div.classList.remove('move-cursor'); 
 
    } 
 
} 
 

 
div.addEventListener('mousedown', changeCursorToMove, false); 
 
div.addEventListener('mouseup', changeCursorToDefault, false); 
 

 
document.oncontextmenu = function(){return false;}
div { 
 
width: 100px; 
 
height: 100px; 
 
background-color: red; 
 
} 
 

 
.move-cursor { 
 
cursor: move; 
 
}
<div></div>

+0

爲什麼在給出幾乎相同的答案之後,你會很好地回答問題,這更符合OP的要求?我試圖理解你浪費時間的邏輯 – vsync

+0

當我正在制定解決方案時,我不在這個頁面上。一旦我的解決方案達到我的滿意,我回到了這個頁面併發布了它。同時你已經發布了你的解決方案。我同意我們的方法非常相似。我會說這可能是一件好事。 – Rounin

+0

它花了你一個小時?而且即使它是重複的,你也發佈了它? – vsync