简体   繁体   English

jQuery拖放color div更改另一个背景

[英]jQuery drag and drop colour div to change background of another

I have the following HTML , containing 4 <div> 's - 2 are doors and 2 are colors, as you can guess from their id . 我有以下HTML ,包含4个<div>的-2是门,2是颜色,您可以从它们的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. 即使有人至少可以指出我正确的方向,我也将不胜感激。

You should initialize your color <div> 's as draggable and door <div> 's as droppable widgets using .draggable() and .droppable() methods respectively. 你应该初始化你的颜色<div>的为拖动和门<div>的作为可放开使用部件.draggable().droppable()分别方法。

Then you can use the drop event handler of droppable for changing the background color. 然后,您可以使用droppabledrop事件处理程序来更改背景颜色。 Inside the handler, you can access the droppable using this and dragged element using ui.draggable as shown below: 在处理程序内部,您可以使用this并使用ui.draggable拖动元素来访问droppable,如下所示:

 $(".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. 旁注:我已经删除了内联css,并使用了css类,以便可以避免样式的重复并保持HTML的整洁。 You can read more about Why Use CSS @ MDN 您可以阅读有关为什么使用CSS @ MDN的更多信息

在“可拖动”的停止事件上,检查哪个div是目标(获取被拖动的div的“ left”和“ top”属性),并使用被拖动的div的颜色对其进行绘制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM