因为本身就绑定了一个onchange事件,就是更换图片的时候会触发这个事件。对于FileReader我就不太懂它的工作原理是什么,懂了以后再补回来
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>显示图片</title>
<script src="<%=request.getContextPath()%>/static/js/jquery-3.4.1.js"></script>
<script>
$(function () {
clickImage()
})
function clickImage() {
$(".image_change").change(function () {
let item = this
let file = this.files[0]
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function (e) {
console.log(this.result.length)
console.log(e)
item.nextElementSibling.setAttribute("src", this.result)
}
})
}
</script>
<style>
.image_upload {
width: 134px;
height: 134px;
position: relative;
border: 1px solid rgb(27, 189, 121);
}
.image_change {
width: 134px;
height: 134px;
display: inline-block;
opacity: 0;
z-index: 99999;
position: absolute;
top: 0px;
left: 0px;
}
.image_show {
display: inline-block;
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="image_upload">
<input type="file" accept="image/*" class="image_change">
<img src="" class="image_show">
</div>
<div class="image_upload">
<input type="file" accept="image/*" class="image_change">
<img src="" class="image_show">
</div>
<div class="image_upload">
<input type="file" accept="image/*" class="image_change">
<img src="" class="image_show">
</div>
</body>
</html>
`效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021051400044932.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzE2NDQ0,size_16,color_FFFFFF,t_70#pic_center)