此脚本允许在上传之前预览/删除图像(通过单击图像)。我唯一的问题是,当我点击图像将其删除时,它会删除这两个图像。
形式:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" style="display:none" id="upload-image" multiple="multiple" name="upload[]"></input>
<div id="upload" class="drop-area">
Upload File
</div>
<div id="thumbnail"></div>
<input type="submit" value="Submit" class="button" name="lesubmit"/>
</form>
JS:
jQuery(function($){
var fileDiv = document.getElementById("upload");
var fileInput = document.getElementById("upload-image");
console.log(fileInput);
fileInput.addEventListener("change",function(e){
var files = this.files
showThumbnail(files)
},false)
fileDiv.addEventListener("click",function(e){
$(fileInput).show().focus().click().hide();
e.preventDefault();
},false)
fileDiv.addEventListener("dragenter",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("dragover",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("drop",function(e){
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
showThumbnail(files)
},false);
function showThumbnail(files){
for(var i=0;i<files.length;i++){
var file = files[i]
var imageType = /image.*/
if(!file.type.match(imageType)){
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
// image.classList.add("")
var thumbnail = document.getElementById("thumbnail");
image.file = file;
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function(aImg){
return function(e){
aImg.src = e.target.result;
};
}(image))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
image.onload= function(){
ctx.drawImage(image,100,100)
}
}
}
$('#thumbnail').on("click", function () {
$('#thumbnail').fadeOut(1000, function() {
$(this).removeProp('src');
$('img').replaceWith(selected_photo = $('img').clone(true));
});
});
});
感谢所有建议!
答案 0 :(得分:1)
根据我的评论,您将要执行以下操作:
$("#thumbnail").on("click", "img", function () {
var image= $(this);
image.fadeOut(1000, function () {
image.removeProp('src').replaceWith(selected_photo = image.clone(true);
});
});
这实际上会淡出图像,从图像中删除源属性,并用克隆替换它。我仍然不理解你正在进行的replaceWith(),所以你可能需要稍微调整一下,但其余部分对你有帮助。