HTML5&CSS3:[3]拖拽图片到浏览器并显示
1、要判断浏览器是否支持html5的file api,可以加上如下代码if (window.File && window.FileReader && window.FileList && window.Blob) {} else { alert('The File APIs are not fully supported in this browser.');}如果不支持,打开页面会有alert信息
2、新建一个html页面,一个div作为文件拖入的区域
![HTML5&CSS3:[3]拖拽图片到浏览器并显示](https://exp-picture.cdn.bcebos.com/8974c38a59de45072f6052c35e413a8ca70885f4.jpg)
3、给div加上dragover和drop事件dragover不需要实现什么功能,它要做的是阻止冒泡,如果不加,drop无效
![HTML5&CSS3:[3]拖拽图片到浏览器并显示](https://exp-picture.cdn.bcebos.com/890dfb4a2f27e7ef9f6701b219dd3340b7f3f5f4.jpg)
5、遍历文件,FileReader读取,并显示。主要代码如下,list为显示的容器var reader = new FileReader();reader.onload = (function(theFile) { return function(e) { var span = document.createElement('span'); span.innerHTML = ['<img src="', e.target.result, '" title="', theFile.name, '"/>'].join(''); document.getElementById('list').insertBefore(span, null); };})(f);reader.readAsDataURL(f);
![HTML5&CSS3:[3]拖拽图片到浏览器并显示](https://exp-picture.cdn.bcebos.com/a9338a1fbee434da363f2090f271fe1d97d8e4f4.jpg)