转行学开发,代码100天——2018-04-10
今天记录一个利用JavaScript实现文件拖拽上传到浏览器,后天将文件打开的小案例。
基本功能:1点击添加文件 2 文件拖拽添加
html:
<div id="box"> <span id="span">选择或拖放文件</span> <input id="browse" type="file"> </div>
css:
#box{ position: relative; border:3px dashed #ddd; width: 200px; height: 70px; text-align: center; line-height: 70px; cursor: pointer; } #box input{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; } #box.hover{ border:3px solid #999; }
javascript:
<script type="text/javascript"> var box = document.getElementById("box"); var input = document.getElementById("browse"); var span = document.getElementById("span"); //box 事件 box.ondragover = function() { this.className = "box hover"; } box.ondragleave = function() { this.className = "box"; } //input 事件 input.ondragover = function(e) { e.preventDefault(); } input.ondrop = function(e) { e.preventDefault(); box.className = "box"; var file = e.dataTransfer.files[0]; show(file); } input.onchange = function() { var file = this.files[0]; show(file); } function show(file) { span.innerHTML = file.name; var fr = new FileReader(); fr.onload = function() { var result = this.result; console.log(result); } fr.readAsText(file); } </script>
案例效果: