<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>file input 选择图片实时预览</title>
<script type="text/javascript">
function getFileObject(sourceId) {
if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox
return window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
} else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome
return window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
} else {
return document.getElementById(sourceId).value;
}
}
function preImg(sourceId, targetId) {
document.getElementById(targetId).src = getFileObject(sourceId);
}
</script>
</head>
<body>
<div>
<form action="">
<input id="imgFile" type="file" accept="image/*" onchange="preImg(this.id,'photo');" style="display:none" />
<img id="photo" onclick="document.querySelector('#imgFile').click();" src="默认图片" alt="上传头像" width="300px" height="300px"
/>
</form>
</div>
</body>
</html>
网友评论