[javascript]代码库
<html>
<head>
<style>
#holder {
border: 10px dashed #ccc;
width: 480px;
height: 600px;
margin: 20px auto;
}
#holder.hover {
border: 10px dashed #333;
}
</style>
</head>
<body>
<section id="wrapper">
<header>
<h1>图片文件拖拽实时预览</h1>
</header>
<article>
<div id="holder"></div>
<p id="status" class="success">支持File API & FileReader</p>
<p>将图片拖拽到上面的框中,图片文件将被作为背景放在区域内, 区域大小固定为480 X600, 图片仅仅在浏览器上预览,并没有上传到任何服务器。</p>
</article>
</section>
<script type="text/javascript">
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = '支持File API & FileReader';
}
holder.ondragover = function () {
this.className = 'hover';
return false;
};
holder.ondragend = function () {
this.className = '';
return false;
};
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
console.log(event.target);
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
console.log(file);
reader.readAsDataURL(file);
return false;
};
</script>
</body>
</html>
[代码运行效果截图]