Skip to content

Instantly share code, notes, and snippets.

@xyqfer
Created September 29, 2013 10:35
Show Gist options
  • Save xyqfer/6751326 to your computer and use it in GitHub Desktop.
Save xyqfer/6751326 to your computer and use it in GitHub Desktop.
拖拽 && 上传
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#box {
border: 2px gray dotted;
width: 180px;
height: 160px;
line-height: 160px;
text-align: center;
}
.hover {
border: 2px olive solid: ;
}
.drop {
border: 2px blue solid;
}
</style>
</head>
<body>
<div id="box"></div>
<input type="file" id="file" value="upload">
<script>
var box = document.getElementById("box"),
file = document.getElementById("file");
file.onchange = function(e) {
var file = this.files[0],
reader = new FileReader();
reader.onload = function() {
box.style.background = "url(" + this.result + ") no-repeat center";
};
reader.onerror = function(e) {
alert(this.error.code);
};
reader.readAsDataURL(file);
};
box.ondragover = function(e) {
this.innerHTML = "can drop here";
this.className = "hover";
e.dataTransfer.dropEffect = "copy";
e.preventDefault();
};
box.ondragleave = function() {
this.innerHTML = "";
this.className = "";
return false;
};
box.ondragend = function() {
this.className = "";
return false;
};
box.ondrop = function(e) {
this.innerHTML = "";
this.className = "drop";
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function(e) {
box.style.background = "url(" + e.target.result + ") no-repeat center";
};
reader.onerror = function(e) {
alert(e.target.error.code);
};
reader.readAsDataURL(file);
e.preventDefault();
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment