Change a background image through a file input

2019-05-14 03:24发布

My question is how to change the background-image of a div to an image selected by an input file element. The file-input is hidden and executed when the user of the site clicks on another input element here is that code:

$(function(){
  $('#verborgen_file').hide();
  $('#uploadButton').on('click',function(){
    $('#verborgen_file').trigger('click');
  });
});

So the file-input is #verborgen_file and the other input is #uploadButton now I'm looking for a way that when the user clicks on #uploadButton and therefore triggers #verborgen_file and choses an image (and only an image) the background-image of the div #pf_foto changes to that chosen image.

I have try'd a lot of things but just couldn't get it to work so in advance Thank You!

----EDIT----

i try'd this:

$("#verborgen_file").on("change", function(){

    var files = !!this.files ? this.files : [];
    if ( !files.length || !window.FileReader ) return;
    if ( /^image/.test( files[0].type ) ) {
        var reader = new FileReader();
        reader.readAsDataURL( files[0] );
        reader.onloadend = function(){
            $("#pf_foto").css("background-image", "url(" + this.result + ")");
        }
    }
});

1条回答
你好瞎i
2楼-- · 2019-05-14 03:43

Take a look to the following code snippet. Hope this will help you.

$('#verborgen_file').hide();
        $('#uploadButton').on('click', function () {
              $('#verborgen_file').click();
        });

        $('#verborgen_file').change(function () {
            var file = this.files[0];
            var reader = new FileReader();
            reader.onloadend = function () {
               $('#pf_foto').css('background-image', 'url("' + reader.result + '")');
            }
            if (file) {
                reader.readAsDataURL(file);
            } else {
            }
        });
#pf_foto {
        background-image: url('');
        background-size: cover;
        background-position: center;
        height: 200px;
        width: 200px;
        border: 1px solid #000;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' id='verborgen_file' />
<input type="button" value="Upload" id="uploadButton" />
<br>
<br>
<div id="pf_foto"></div>

查看更多
登录 后发表回答