javascript - 在使用javascript在html中上传图像之前显示缩略图不起作用
问题描述
我有一个用 html 设计的表单,该表单有 2 张图片上传,我试图在用户提交表单之前向他显示缩略图,我有以下代码:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imaged')
.attr('src', e.target.result);
};
reader.onload = function(e) {
$('#imageds')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
<div class="col-sm-4">
<img id="imaged" style="width:150px; height: 150px; border-radius:50%;" src="" alt="image">
<input onchange="readURL(this);" type="file" name="" class="form-control" style="margin-top:2%;">
</div>
<div class="col-sm-4">
<img style="width:150px; height: 150px; border-radius:50%;" src="" alt="image">
<input id="imageds" type="file" onchange="readURL(this);" name="" class="form-control" style="margin-top:2%;">
</div>
但是,这不会将图像显示为缩略图,而只是在“选择文件”按钮附近显示图像名称。谁能告诉我这里可能出了什么问题,在此先感谢
解决方案
- 您忘记在 readURL() 中关闭大括号
- 您将 id 图像放错位置以输入标签而不是图像标签
所以最终的代码就像
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imaged')
.attr('src', e.target.result);
};
reader.onload = function(e) {
$('#imageds')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4">
<img id="imaged" style="width:150px; height: 150px; border-radius:50%;" src="" alt="image">
<input onchange="readURL(this);" type="file" name="" class="form-control" style="margin-top:2%;">
</div>
<div class="col-sm-4">
<img id="imageds" style="width:150px; height: 150px; border-radius:50%;" src="" alt="image">
<input type="file" onchange="readURL(this);" name="" class="form-control" style="margin-top:2%;">
</div>
推荐阅读
- google-cloud-dataflow - 如何使用 Apache Beam Python SDK 在两组 json 存储桶上执行“差异”?
- r - 如何修复“FUN中的错误(X [[i]],...):运算符'<-'未实现”在R中
- c# - azure 服务总线的 Azure Function App 延迟重试
- r - 如何洗牌表示为R中总和的函数的一部分?
- java - 向注册表中的环境添加多个值并在 Java 应用程序中检索
- php - 使用php在一段时间后动态更改网站背景
- laravel - 显示多对多关系的结果和单独的结果,而不考虑它们的 id
- python - 如何在matplotlib pyplot的y轴上为间隔组添加标签?
- python - 如何使用 tensorflow 实现类似于 Conv2D 的这一层?
- git - git rebase 丢失了我的更改。我有详细的历史。知道出了什么问题吗?