HTML5&CSS3:[3]拖拽图片到浏览器并显示

2024-10-19 13:38:30

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]拖拽图片到浏览器并显示

3、给div加上dragover和drop事件dragover不需要实现什么功能,它要做的是阻止冒泡,如果不加,drop无效

HTML5&CSS3:[3]拖拽图片到浏览器并显示

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]拖拽图片到浏览器并显示
猜你喜欢