Created
August 23, 2017 06:51
-
-
Save luobotang/3c98019756470994a61e83be045afd36 to your computer and use it in GitHub Desktop.
Image_Drag_Preview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Image Drag Preview</title> | |
<style> | |
* { margin: 0; padding: 0; } | |
#box { padding: 10px; min-height: 500px; background: #f0f0f0; } | |
#box img { display: block; max-width: 100%; } | |
</style> | |
</head> | |
<body> | |
<div id="box"></div> | |
<script> | |
(function () { | |
var box = document.getElementById('box') | |
var URL = window.URL || window.webkitURL | |
if (!URL) { | |
alert('require "window.URL"') | |
return | |
} | |
box.addEventListener('dragenter', stopEvent, false) | |
box.addEventListener('dragover', stopEvent, false) | |
box.addEventListener('drop', function (e) { | |
stopEvent(e); | |
try { | |
var files = e.dataTransfer.files | |
if (!files || files.length === 0) { | |
alert('no files') | |
return | |
} | |
var file = files[0] | |
if (/^image\//.test(file.type)) { | |
var img = document.createElement('img') | |
img.src = URL.createObjectURL(file) | |
img.onload = () => URL.revokeObjectURL(this.src) | |
box.appendChild(img) | |
} else { | |
alert('not image file') | |
} | |
} catch(e) { | |
alert(e) | |
} | |
}, false) | |
function stopEvent(e) { | |
e.stopPropagation(); | |
e.preventDefault(); | |
} | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment