2017-03-01 53 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