【发布时间】:2020-04-26 11:40:25
【问题描述】:
我有 3 个容器,其中前两个具有拖放功能,因此当我将元素放在那里时,它会更改容器颜色。这可以正常工作,但我想做的是,当第一个和第二个容器有颜色时,第三个容器会自动更新为新颜色。我正在使用 Vuejs。
例如:容器 1 为红色,容器 2 为黄色。第三个容器会自动更新为橙色。每次我更改容器的颜色时都会发生这种情况。
这是我的代码:
HTML
<!-- the containers where I drop the elements -->
<div class="box-flex">
<div class="box" @dragover.prevent @drop="drop" id="box-1"></div>
<div class="box" @dragover.prevent @drop="drop2" id="box-2"></div>
<div class="box" id="box-3"></div>
</div>
<!-- the elements I want to drag -->
<div v-for="(flower, i) in flowers" :key="i">
<div v-if="flower_type == flower.type">
<p>{{ flower.type }}</p>
<p v-for="(color, j) in flower.colors" :key="j">
<span
:id="flower.type + '-' + color"
:draggable="true"
@dragstart="dragStart"
@dragover.stop
>{{ color }}</span>
</p>
</div>
</div>
脚本
data() {
return {
//flowers
flowers: [
{
type: "Cosmos",
colors: ["red", "yellow", "orange", "black", "pink", "white"]
},
],
};
},
methods: {
dragStart(e) {
let target = e.target;
e.dataTransfer.setData("color_id", target.id);
e.dataTransfer.setData("box_el", target);
let box1 = document.getElementById("box-1");
},
//first container drop
drop(e) {
let colorId = e.dataTransfer.getData("color_id"); //id of the color (red, yellow...)
let colorEl = e.dataTransfer.getData("box_el"); //element of the color
let box1 = document.getElementById("box-1");
box1.classList.add(colorId);
if (box1.classList.length > 2) { //I only want one color-class in the container
box1.classList.remove(box1.classList[1]);
}
},
//second container drop
drop2(e) {
let colorId = e.dataTransfer.getData("color_id"); //id of the color (red, yellow...)
let colorEl = e.dataTransfer.getData("box_el"); //element of the color
let box2 = document.getElementById("box-2");
box2.classList.add(colorId);
if (box2.classList.length > 2) {
box2.classList.remove(box2.classList[1]);
}
}
},
computed: {
evFlower() {
let box1 = document.getElementById("box-1");
let box2 = document.getElementById("box-2");
let box3 = document.getElementById("box-3");
if (
box1.classList.contains("Cosmos-red") &&
box2.classList.contains("Cosmos-yellow")
) {
box3.classList.add("Cosmos-orange");
}
}
}
CSS
.box-flex {
height: 50%;
display: flex;
justify-content: space-around;
align-items: center;
}
.box,
.box-1,
.box-2 {
width: 20%;
height: 20%;
border: 2px solid black;
}
.Cosmos-red {
background: red;
}
.Cosmos-yellow {
background: yellow;
}
.Cosmos-orange {
background: orange;
}
我尝试过使用观察者,但没有找到“观察”DOM 变化的方法。
提前致谢!!
【问题讨论】:
-
堆栈溢出不需要感谢,它使内容更难阅读。请编辑您的问题。
标签: javascript css vue.js drag-and-drop