我让这个 JavaScript 在用户选择文件时显示图像预览,它正在工作。
案例:
- 如果用户选择错误的图像并将其删除,则预览不会刷新为“空”。
我不知道该怎么做,已经浏览了谷歌和 stackoverflow,但什么也没有。有人能给我一盏灯吗?
<img id="image1" width="300px" height="300px"/>
<img id="image2" width="300px" height="300px"/>
<img id="image3" width="300px" height="300px"/>
<img id="image4" width="300px" height="300px"/>
<script>
document.getElementById("productimage1").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image1").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
document.getElementById("productimage2").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image2").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
document.getElementById("productimage3").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image3").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
document.getElementById("productimage4").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image4").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
</script>
最佳答案
如果我正确地得到了你想要的东西......
您希望当用户尝试使用“打开文件”窗口选择新图像时清除图像预览。没有删除按钮。
这是你应该做的:
// A delete function
$("[id^='product']").on("click",function(){
// This clears the input value.
$(this).val("");
// This resets the preview.
var imageID = $(this).attr("id").substr(7);
$("#"+imageID).attr("src","https://placehold.it/300x300");
});
参见CodePen
---编辑
这是完整的代码优化。
// A delete function
$("[id^='product']").on("click",function(){
// This clears the input value.
$(this).val("");
// This resets the preview.
var imageID = $(this).attr("id").substr(7);
$("#"+imageID).attr("src","https://placehold.it/300x300");
});
// The preview function
$("[id^='product']").on("change",function(){
var imageID = $(this).attr("id").substr(7);
// Displays a preview im the right div
var reader = new FileReader();
reader.onload = function (e) {
$("#"+imageID).attr("src",e.target.result);
};
reader.readAsDataURL(this.files[0]);
});
关于javascript - 当我在输入文件中插入文件时,它会显示预览,但如何删除选定的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43160210/