很多时候我们要进行图片处理,在图片未上传时进行预览效果。这里进行原生js的最简单的实现,以适应不同的开发调整。
Talk is cheap,show me your code ~
<title>图片上传预览</title>
<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this)">
<div id="fileList" style="width:200px;height:200px;"></div>
<script>
window.URL = window.URL || window.webkitURL;
var fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
function handleFiles(obj) {
var files = obj.files;
for(var _i=0;_i<files.length;_i++){
var img = new Image(200);
if(window.URL){
img.src = window.URL.createObjectURL(files[_i]);
//img.width = 200;
img.onload = function(e) {
window.URL.revokeObjectURL(this.src);
}
fileList.appendChild(img);
}else if(window.FileReader){
//opera不支持createObjectURL/revokeObjectURL方法。我们用FileReader对象来处理
var reader = new FileReader();
reader.readAsDataURL(files[_i]);
reader.onload = function(e){
img.src = this.result;
//img.width = 200;
fileList.appendChild(img);
}
}else{
//ie
obj.select();
obj.blur();
var nfile = document.selection.createRange().text;
document.selection.empty();
img.src = nfile;
//img.width = 200;
fileList.appendChild(img);
}
}
}
</script>