jQuery拖放颜色div来改变另一个的背景 [英] jQuery drag and drop colour div to change background of another

查看:220
本文介绍了jQuery拖放颜色div来改变另一个的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 HTML ,其中包含4个< div> 颜色,你可以从他们的 id 猜到。

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.

推荐答案

您应该初始化您的颜色< div> =http://jqueryui.com/draggable/ =nofollow> draggable and door < div> 'as .draggable()和的http://jqueryui.com/droppable/ =nofollow> droppable 小部件。 drop pable()方法。

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

然后您可以使用 droppable 的#event-droprel =nofollow> drop 事件处理程序颜色。在处理程序中,您可以使用 this 访问droppable,并使用 ui.draggable 拖动元素,如下所示:

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>

/ code>

我删除了内联css和使用css类,这样,你可以避免样式的重复和保持你的HTML干净。您可以阅读有关为什么使用CSS @ MDN

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

这篇关于jQuery拖放颜色div来改变另一个的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆