切换光标以显示我可以放置元素的位置

Chr*_*ris 7 html javascript jquery jquery-ui

我有一个很明显的问题/任务,我仍然想知道为什么我找不到解决方案......

在使用jQuery UI的JavaScript应用程序中,我使用draggable()droppable()API来移动元素.这可以直接按预期进行.
但是现在我想改变鼠标光标,使其显示我可以放置元素(cursor: "copy")或不可能放置的位置(cursor: "no-drop").

这当然应该只在拖动过程中发生,否则应该显示正常的光标.

注意:可以假设仅在一个特殊情况下允许丢弃<div>(例如,由id或标识class),并且在其他任何地方都不允许丢弃.

T J*_*T J 5

您可以使用开始事件回调使用方法将可拖动的光标样式设置为no-drop拖动时,并在事件回调中将其更改为在可放置的上方时。css()copyover

一旦draggable离开droppable,您可以将光标恢复到事件回调no-drop内,并通过将CSS属性值out设置为draggable的停止事件回调内,在拖动停止时将其重置回默认光标,如下所示:cursorinitial

$(function() {
  $("#draggable").draggable({
    start: function(event,ui){
     $(this).css("cursor", "no-drop");
    },
    stop: function(event,ui){
     $(this).css("cursor", "initial");
    }
  });
  $("#droppable").droppable({
    over: function(event, ui) {
      ui.draggable.css("cursor", "copy");
    },
    out: function(event, ui) {
      ui.draggable.css("cursor", "no-drop");
    }
  });
});
Run Code Online (Sandbox Code Playgroud)
div {
  display: inline-block;
  margin: 20px;
  text-align: center;
}
#draggable {
  width: 50px;
  height: 50px;
  line-height: 50px;
  background: dodgerblue;
}
#droppable {
  width: 100px;
  height: 100px;
  line-height: 100px;
  background: hotpink;
}
Run Code Online (Sandbox Code Playgroud)
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div id="draggable">
  <span>Drag</span>
</div>

<div id="droppable">
  <span>Drop here</span>
</div>
Run Code Online (Sandbox Code Playgroud)