jQuery UI dragging, update target element

情到浓时终转凉″ 提交于 2019-12-13 21:07:45

问题


I am trying to develop a page that will allow users to drag an element(like a DIV) to another DIV.

Once the dragged element is over the target div and the user lets go of the mouse, the target div should have something happen to it. For example it should change colour and have some text inserted into it.

So basically what I want is for some how to know that the element has been dropped on the target div so that I can manipulated the target div however I want.

Here is my jsfiddle prototype. http://jsfiddle.net/WhesleyBarnard/3Lnxnc4o/1/ The target div is the big green div.

So to answer my question I only need you guys to help me change the target divs colour and text as soon as the element is dropped on it.

Thanking you in advance.

Current Code Extract
HTML

<div id="div1"><div></div></div>
<div id="div2"></div>

CSS

#div1 {
    height: 100px;
    background-color: red;
    margin-bottom: 50px;
    padding: 5px;
}
#div1 div {
    width: 30px;
    height: 30px;
    border: solid 1px black;
}
#div2 {
    height: 100px;
    background-color: green;
    padding: 5px;
}

jQuery

$(document).ready(function() {
    $('#div1 div').draggable({
        cursor: "none",
        revert: true
    });
});

回答1:


You should make your target <div> a droppable element using droppable() method, then you can use the drop event callback to detect when an item is dropped and manipulate the droppable using this keyword:

$(document).ready(function() {
  $('#div1 div').draggable({
    cursor: "none",
    revert: true
  });
   $('#div2').droppable({
     drop:function(){
         $(this).css("background","dodgerblue").text("Something is dropped!")
     }
  });
});
#div1 {
    height: 50px;
    background-color: red;
    margin-bottom: 50px;
    padding: 5px;
}
#div1 div {
    width: 30px;
    height: 30px;
    border: solid 1px black;
}
#div2 {
    height: 50px;
    background-color: green;
    padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<div id="div1"><div></div></div>
<div id="div2"></div>


来源:https://stackoverflow.com/questions/26211562/jquery-ui-dragging-update-target-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!