我已经自定义了我的表单上传按钮并通过 css display:none
隐藏了 input
字段,但是当我选择一个图像时,输入没有显示预览文本!
我想显示所选图像的预览文本,以便用户知道他已经选择了图像!
HTML:
<div class="form-group">
<label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
<input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">
<span>No file chosen</span>
</div>
CSS:
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
input[type=file] {
display: none;
}
input[type=file]{
display:none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<div class="form-group">
<label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
<input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image"> <span>No file chosen</span>
</div>
更新:我尝试了所有这些解决方案 ( How to display file name for custom styled input file using jquery? ),但没有一个对我有用。在我的场景中,我有两个上传按钮,一个是 before image upload
,第二个是 after image upload
,如视频所示。
我仍然无法在上传按钮前显示预览文本。
最佳答案
只需在 onchange 事件的输入类型文件中添加一个新函数。请找到附件中的代码。
input[type=file]{
display:none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<div class="form-group">
<label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
<input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image" onChange="((e)=>{
file = e.target.files.item(0);
var fr = new FileReader;
fr.onloadend =(imgsrc)=>{
imgsrc = imgsrc.target.result; // file reader
var img = document.createElement('img');
img.src =imgsrc;
this.nextSibling.nextSibling.innerHTML='';
this.nextSibling.nextSibling.appendChild(img);
};
fr.readAsDataURL(file);
})(event)">
<span>No file chosen</span>
</div>
关于javascript - 为什么图片上传不显示图片预览文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56376381/