在光标不移动时更改光标

时间:2017-03-01 10:38:04

标签: javascript jquery html css cursor

所以我有一个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>

所以基本上,我希望光标改为&#39; cursor:move;&#39;每当用户按住鼠标右键时;但是,会发生以下情况:

  • initial: cursor:default
  • 鼠标按下:光标:默认
  • 鼠标移动:光标:默认
  • 鼠标向上:光标:移动
  • 鼠标移动:光标:默认

所以现在我的问题是:为什么会发生这种情况,以及解决问题的好方法是什么?

PS:在chrome中测试过,这是我需要使用它的主要浏览器

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以附加mousedownmouseup个事件来启动将更改和恢复光标的功能。

在每个功能中,您可以确认刚刚按下(或释放)的按钮是鼠标右键。

工作示例:

&#13;
&#13;
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;}
&#13;
div {
width: 100px;
height: 100px;
background-color: red;
}

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