簡體   English   中英

在不移動時更改光標

[英]Changing the cursor while it's not moving

因此,我有一個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>

所以基本上,我希望光標更改為“ cursor:move;”。 每當用戶按住鼠標右鍵時; 但是,發生以下情況:

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

所以現在我的問題是:為什么會發生這種情況,什么是解決它的好方法?

PS:經過chrome測試,這是我需要使用的主要瀏覽器

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

您可以附加mousedownmouseup事件來啟動將更改和還原光標的功能。

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

工作示例:

 var div = document.getElementsByTagName('div')[0]; function changeCursorToMove(event) { if ((event.which === 3) || (event.button === 2)) { div.classList.add('move-cursor'); } } function changeCursorToDefault(event) { 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> 

暫無
暫無

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

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