通过 JavaScript 实现图片的本地预览(无需上传至服务器),兼容所有浏览器
css:
.wrap{
width: 202px;
margin: 80px auto;
}
#preview, .img, img{
width:200px;
height:200px;
}
#preview{
border:1px solid #000;
}
html:
<div class="wrap">
<div id="preview"></div>
<input type="file" accept="image/*" onchange="preview(this)"/>
</div>
js:
function preview(file){
var prevDiv = document.getElementById('preview');
if (file.files && file.files[0]){
var reader = new FileReader();
reader.onload = function(event){
prevDiv.innerHTML = '<img src="' + event.target.result +'"/>';
}
reader.readAsDataURL(file.files[0]);
}
else{
prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
}
}
(完)
( 0 )个小伙伴在吐槽