我正在尝试创建一个html表,您可以在其中将项目从单元格拖放到单元格。我设法找到一些相关的代码并修改了这个例子,这就是结果:
HTML:
<table id="#our_table" border="1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td>
<span class="event" id="item1" draggable="true">Item 1</span>
</td>
<td>
<span class="event" id="item2" draggable="true">Item 2</span>
<span class="event" id="item3" draggable="true">Item 3</span>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
CSS:
table th, table td {
width: 200px;
height:70px;
padding: 5px;
}
table span {
display:block;
background-color: #ccc;
border: 1px solid black;
color: fff;
height: 30px;
width: 100%;
}
JavaScript的:
$(document).ready(function() {
$('.event').on("dragstart", function(event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).attr('id'));
});
$('table td').on("dragenter dragover drop", function(event) {
event.preventDefault();
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text', $(this).attr('id'));
de = $('#' + data).detach();
if (event.originalEvent.target.tagName === "SPAN") {
de.insertBefore($(event.originalEvent.target));
} else {
de.appendTo($(this));
}
};
});
})
我该怎么做?