" alt="car2" />
<img draggable="true" id="car3" src="/uploadfile/201307/26/41103534162.jpg" alt="car3" />
<div id="target">
<p id="msg">
drop here</p>
</div>
</div>
<script>
var src = document.getElementById("src");
var target = document.getElementById("target");
target.ondragenter = handleDrag;
target.ondragover = handleDrag;
function handleDrag(e) {
e.preventDefault();
}
target.ondrop = function (e) {
var droppedID = e.dataTransfer.getData("Text");
var newElem = document.getElementById(droppedID).cloneNode(false);
target.innerHTML = "";
target.appendChild(newElem);
e.preventDefault();
}
src.ondragstart = function (e) {
e.dataTransfer.setData("Text", e.target.id);
e.target.classList.add("dragged");
}
src.ondragend = function (e) {
var elems = document.querySelectorAll(".dragged");
for (var i = 0; i < elems.length; i++) {
elems[i].classList.remove("dragged");
}
}
</script>
</body>
</html>
5.拖拽文件 html5支持file api,可以让我们操作本地文件。一般我们不直接使用file api,我们可以结合其他特性一起使用,比如结合拖拽特效,如下例:
复制代码代码如下:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
body > *
{
float: left;
}
#target
{
border: medium double black;
margin: 4px;
height: 75px;
width: 200px;
text-align: center;
display: table;
}
#target > p
{
display: table-cell;
vertical-align: middle;
}
table
{
margin: 4px;
border-collapse: collapse;
}
th, td
{
padding: 4px;
}
</style>
</head>
<body>
<div id="target">
<p id="msg">
Drop Files Here</p>
</div>
<table id="data" border="1">
</table>
<script>
var target = document.getElementById("target");
target.ondragenter = handleDrag;
target.ondragover = handleDrag;
function handleDrag(e) {
e.preventDefault();
}
target.ondrop = function (e) {
var files = e.dataTransfer.files;
var tableElem = document.getElementById("data");
tableElem.innerHTML = "<tr><th>Name</th><th>Type</th><th>Size</th></tr>";
for (var i = 0; i < files.length; i++) {
var row = "<tr><td>" + files[i].name + "</td><td>" + files[i].type + "</td><td>" + files[i].size + "</td></tr>";
tableElem.innerHTML += row;
}
e.preventDefault();
}
</script>
</body>
</html>
DataTransfer返回FileList对象,我们可以把他当做file数组对象,file包含下面属性:name:文件名字;type:文件类型(MIME类型);size:文件大小。
运行效果:
6.上传文件 下面介绍一个通过拖拽ajax上传文件的实例。
复制代码代码如下:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
.table
{
display: table;
}
.row
{
display: table-row;
}
.cell
{
display: table-cell;
padding: 5px;
}
.label
{
text-align: right;
}
#target
{
border: medium double black;
margin: 4px;
height: 50px;
width: 200px;
text-align: center;
display: table;
}
#target > p
{
display: table-cell;
ve