简体   繁体   English

取消文件上传时删除图像预览

[英]Removing an image preview when file upload is cancelled

I am trying to preview an image before uploading it.To that end, i have an which will load the picture whenever a user uploads a picture. 我试图在上传之前预览图像。为此,我有一个在用户上传图片时将其加载的图片。

By clicking the image that is preview, the user is able to cancel the upload, and the image previewed will disappear.However, if the user has already selected an image, and then click ' cancel ' when choosing a file to upload(because he changed his mind etc), the image that was previously selected will still remain, and will not disappear. 通过单击预览图像,用户可以取消上传,预览的图像将消失。但是,如果用户已经选择了图像,然后在选择要上传的文件时单击“ 取消 ”(因为他改变主意等),先前选择的图像仍将保留,并且不会消失。

Is there anyway to remove the image that was previewed in this case? 无论如何,在这种情况下是否要删除预览的图像?

HTML: HTML:

<input type='file' id='input1'>
<img id='imagepreview1'>

jQuery: jQuery的:

$(document).ready(function(){

    function readURL(input) {        
        if (input.files && input.files[0]) {
            var reader = new FileReader();        
            reader.onload = function (e) {
                $('#imagepreview1').prop('src', e.target.result).show();
            }        
            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#input1").change(function () {
        readURL(this);
        $('#imagepreview1').show();
    });

    $('#imagepreview1').click(function(){        
        $('#input1').replaceWith($('#input1').clone(true));
        $('#imagepreview1').hide();        
    });

});

Remove the src of image every time you click , 每次单击都删除图像的src

$("#input1").click(function () {    
    $('#imagepreview1').attr('src','');
});

DEMO DEMO

I'd do something like adding a class to the image if it's been changed, and then either hide it or update its src later: 我会做一些类似的事情,如果更改了图像,则将其添加到图像中,然后将其隐藏或稍后更新其src:

http://jsfiddle.net/isherwood/LCrE4/3 http://jsfiddle.net/isherwood/LCrE4/3

$('#imagepreview1').prop('src', e.target.result).show().addClass('selected');

... ...

var orig_src = $('#imagepreview1').prop('src');

$('#imagepreview1').click(function () {    
    $('#input1').replaceWith($('#input1').clone(true));
    $('#imagepreview1').not('.selected').hide();
    $('#imagepreview1.selected').prop('src', orig_src).removeClass('selected');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM