用html和js写一个图片预览的功能
时间: 2023-12-24 13:06:19 浏览: 23
实现图片预览功能
<!DOCTYPE html>
<html>
<head>
<title>图片预览</title>
<meta charset="utf-8">
<style>
#preview {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
}
</style>
</head>
<body>
<input type="file" id="fileInput">
<div id="preview"></div>
<script>
var fileInput = document.getElementById("fileInput");
var preview = document.getElementById("preview");
fileInput.addEventListener("change", function() {
var file = this.files[0];
if (file) {
var reader = new FileReader();
reader.addEventListener("load", function() {
preview.innerHTML = '<img src="' + reader.result + '">';
preview.style.display = "block";
});
reader.readAsDataURL(file);
}
});
preview.addEventListener("click", function() {
this.style.display = "none";
});
</script>
</body>
</html>
阅读全文