JSFiddle - React, Tailwind, and code Playground
by acwong
HTML
<div id="container">
<p>拖动不同颜色的方块到正方形的区域,然后弹框中显示相应颜色。颜色名称通过dataTransfer传递。</p>
<div id="box">drop in!</div>
<ul id="colors">
<li draggable="true" id="red">red</li>
<li draggable="true" id="yellow">yellow</li>
<li draggable="true" id="blue">blue</li>
</ul>
</div>
CSS
ul,li {
margin: 0;
padding: 0;
list-style: none;
}
#container {
width: 500px;
overflow: hidden;
text-align: center;
}
#box {
float: left;
width: 170px;
height: 170px;
border: 1px solid #000;
background-color: #FFF;
line-height: 170px;
}
#colors {
float: right;
}
#colors li {
width: 150px;
height: 50px;
margin-bottom: 10px;
line-height: 50px;
}
#red {
background-color: red;
}
#yellow {
background-color: yellow;
}
#blue {
background-color: blue;
}
JavaScript
(function dragColor(){
var dropBox = document.getElementById('box');
var dragColors = document.getElementById('colors').getElementsByTagName('li');
for (var i = 0; i < dragColors.length; i++) {
dragColors[i].addEventListener('dragstart', function(event){
color = event.target;
event.dataTransfer.setData('Text','The color is ' + this.id);
}, false);
}
dropBox.addEventListener('dragenter', function(event){
event.preventDefault();
}, false);
dropBox.addEventListener('dragover', function(event){
event.preventDefault();
}, false);
dropBox.addEventListener('drop', function(event){
this.style.backgroundColor = color.innerHTML;
this.innerHTML = color.innerHTML;
alert(event.dataTransfer.getData('Text'));
}, false);
})();