看了某大佬的文章,看到了H5中的拖拽功能,有点感兴趣
于是就有了后来的事
想完成一个简单的拖拽时,获取到其元素的背景颜色,然后放在承接的元素里面,将目标元素的背景色修改成相同颜色
即将其中一个盒子拖到目标点后,目标盒子的背景色变为与拖拽盒子一样的
问题即出现了
发现到并不能拖过dom.style.backgroundColor拿到对应元素的背景颜色,只能进行修改
function drag(ev) {
console.log(ev.target.id);
console.log("通过dom.style.backgroundColor拿",ev.target.style.backgroundColor);
const data=getComputedStyle(ev.target).backgroundColor;
console.log(data);
ev.dataTransfer.setData("Text", data);
}
最后是面对搜索引擎编程,可以通过window.getComputedStyle(dom对象).css元素拿到背景颜色并存储,最终实现功能
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.green {
width: 100px;
height: 100px;
background-color: #ff7630;
}
.red {
width: 100px;
height: 100px;
background-color: red;
}
.yellow {
width: 100px;
height: 100px;
background-color: yellow;
}
.blue {
width: 100px;
height: 100px;
background-color: blue;
}
.container {
display: flex;
justify-content: space-around;
align-items: center;
}
.target {
width: 200px;
height: 200px;
border: 2px solid sandybrown;
flex-wrap: wrap;
position: relative;
left: 45%;
text-align: center;
line-height: 200px;
}
</style>
</head>
<body>
<div class="container">
<div class="green" id="box1" draggable="true" ondragstart="drag(event)">
</div>
<div
class="red"
id="box2"
draggable="true"
ondragstart="drag(event)"
></div>
<div
class="yellow"
id="box3"
draggable="true"
ondragstart="drag(event)"
></div>
<div
class="blue"
id="box4"
draggable="true"
ondragstart="drag(event)"
></div>
</div>
<div
class="target"
ondragover="allowDrop(event)"
ondrop="drop(event)"
>目标盒子</div>
<script>
function drag(ev) {
console.log(ev.target.id);
console.log("通过dom.style.backgroundColor拿",ev.target.style.backgroundColor);
const data=getComputedStyle(ev.target).backgroundColor;
console.log(data);
ev.dataTransfer.setData("Text", data);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
console.log(data);
ev.target.style.backgroundColor = data;
}
function allowDrop(ev) {
ev.preventDefault();
}
</script>
</body>
</html>