jQuery drag and drop colour div to change background of another

假装没事ソ 提交于 2019-12-08 04:14:07

问题


I have the following HTML, containing 4 <div>'s - 2 are doors and 2 are colors, as you can guess from their id.

I'd like to be able to drag either colour to either door (such as blue on the left door and black on the right) and change the background colour on the style.

<div id="door1" style="background: #fff;"></div>
<div id="door2" style="background: #fff;"></div>
<div id="black"></div>
<div id="blue"></div>

I'd be grateful even if someone could point me in the right direction at least.


回答1:


You should initialize your color <div>'s as draggable and door <div>'s as droppable widgets using .draggable() and .droppable() methods respectively.

Then you can use the drop event handler of droppable for changing the background color. Inside the handler, you can access the droppable using this and dragged element using ui.draggable as shown below:

$(".color").draggable({
  revert:true
});
$(".door").droppable({
  drop: function(e, ui) {
    console.log(ui.draggable)
    $(this).css("background-color", ui.draggable.attr("id"));
  }
});
.door {
  display: inline-block;
  width: 50px;
  height: 120px;
  border: 1px solid;
  margin: 5px;
}
.color {
  float: right;
  width: 50px;
  height: 50px;
}
.white {
  background: #fff;
}
#black {
  background: #000;
}
#blue {
  clear: left;
  background: royalblue;
}
<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.min.js"></script>
<div id="door1" class="door white"></div>
<div id="door2" class="door white"></div>
<div id="black" class="color"></div>
<div id="blue" class="color"></div>

Side note: I've removed the inline css and is using css classes, So that you can avoid duplication of styles and keep your HTML clean. You can read more about Why Use CSS @ MDN




回答2:


On the stop event of "draggable" check which div was the target (getting 'left' and 'top' attributes of the div that was dragged) and paint it with the color from the div that was dragged.



来源:https://stackoverflow.com/questions/26555606/jquery-drag-and-drop-colour-div-to-change-background-of-another

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