我正在尝试为学习目的重新创建魔兽世界动作栏.
到目前为止,我有吧,个别插槽是Droppable.当黄色div落入容器内部时,我可以这样做,它是否位于.item div内?
@{ ViewBag.Title = "Home Page"; } <script language="JavaScript"> $(function () { $(".draggable").draggable(); $(".item").droppable({ drop: function (event,ui) { $(this) .addClass("ui-state-highlight") .find("p") .html("Dropped!"); } }); }); </script> <div class="draggable"> </div> <div class="bar"> <div class="item"> <p>a</p> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> </div>
解决方法
这个怎么样:
$(function() { $(".draggable").draggable(); $(".item").droppable({ drop: function(event,ui) { var $this = $(this); $this.append(ui.draggable); var width = $this.width(); var height = $this.height(); var cntrLeft = width / 2 - ui.draggable.width() / 2; var cntrTop = height / 2 - ui.draggable.height() / 2; ui.draggable.css({ left: cntrLeft + "px",top: cntrTop + "px" }); } }); });
编辑:我注意到你在目标div中有一些文字.如果您希望这可以与droppable中的其他元素一起使用,则可以绝对定位拖动的元素,并使用父元素的左侧和顶部来对其进行偏移:
var width = $this.width(); var height = $this.height(); var top = $this.offset().top; var left = $this.offset().left; var cntrLeft = (width / 2 - ui.draggable.width() / 2) + left; var cntrTop = (height / 2 - ui.draggable.height() / 2) + top;
和:
ui.draggable.css({ left: cntrLeft + "px",top: cntrTop + "px",zIndex:1,position: 'absolute' });
笔记:
> ui.draggable是放置在droppable上的可拖动项目.
> $this.append(ui.draggable)将拖动的项目附加到droppable div,以便可以准确地完成定位.