本地預覽圖片html和js例子,直接上代碼吧。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>測試本地圖片預覽</title>
</head>
<body>
<div>
<div id="preview_div" style="width: 200px; height: 200px; border: 1px solid #b6ff00; cursor: pointer;" onclick="previewFunc();">
<img id="preview_img" style="width:100%;height:200px;"/>
<input id="upload_img" type="file" style="width:0px;height:0px;" />
</div>
</div>
</body>
</html>
<script type="text/javascript">
function previewFunc()
{
document.getElementById("upload_img").click();
}
//值改變的話
document.getElementById("upload_img").onchange = function () {
var sender = this;
if (!sender.value.match(/.jpg|.gif|.png|.bmp/i)) {
alert('圖片格式無效!');
return false;
}
var objPreviewImg = document.getElementById('preview_img');
var objPreviewDiv = document.getElementById('preview_div');
if (navigator.userAgent.indexOf("MSIE") > -1) {
//IE瀏覽器的話
try {
objPreviewImg.src = createFileObj(this.files[0]);
}
catch (e) {
//ie7中不兼容出錯跳到這裏
this.select(); //選擇的時候
top.parent.document.body.focus(); //若是要嵌套到iframe中進行顯示的話,須要加這個將焦點聚到iframe裏面
this.blur(); //必需要加這個
var src = document.selection.createRange().text; //IE 11中改成以下:document.selection ---》 window.getSelection
document.selection.empty();
objPreviewImg.style.display = "none"; //隱藏img控件
objPreviewDiv.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
objPreviewDiv.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
}
} else {
//chrome firfox均可以
objPreviewImg.src = createFileObj(this.files[0]);
}
}
function createFileObj(filePath)
{
var url = null;
if (window.createObjectURL != undefined) {
url = window.createObjectURL(filePath);
} else if (window.URL != undefined) {
url = window.URL.createObjectURL(filePath);
} else if (window.webkitURL != undefined) {
url = window.webkitURL.createObjectURL(filePath);
}
else {
}
return url;
}
</script>