简体   繁体   中英

Changing the cursor while it's not moving

so I have a webapplication (in html,css and javascript, jquery) that drags an element around (meaning, the cursor doesn't move over that element since the element is moving with the cursor). I wish to change the cursor to a 'move' cursor, but I'm encountering this weird behaviour. I wrote this bit of code to demonstrate:

<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>

So basically, I want the cursor to changing to 'cursor:move;' whenever the user is holding the right mouse button; But, the following happens:

  • initial: cursor: default
  • mouse down: cursor: default
  • mouse move: cursor: default
  • mouse up: cursor: move
  • mouse move: cursor: default

so now my question is: why does this happen, and what would be a good way to fix it?

PS: tested in chrome, this is the main browser I need this to work in

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 

Attaching the mousedown and mouseup events on the document itself and making them both call the same function which simply check the button clicked. right = 2 in your case.

You can attach mousedown and mouseup events to initiate functions which will change and revert the cursor.

Within each function you can confirm that the button just pressed (or released) is the right mouse button.

Working Example:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM