How to view uploaded image as background image div?

I want to view the downloaded image file in a div. I did some research, and I found this piece of code this post , this is the code to preview the downloaded image file, but in the <img>tag:

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

Related HTML:

<body>
    <form id="form1" runat="server">
        <input type='file' onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Very cool. However, I want to show the loaded image as a background image of a div, an example of which would be the following:

<div class="image" style="background-image:url('');"></div>

I know that, logically, I would have to replace

$('#blah').attr('src', e.target.result);

with something like

$('div.image').attr('style', e.target.result);.

But how to make the image path go to the value of the background-image property?

And yes, do I need to link the jQuery library to it?

Thank.

+5
source share
1 answer

CSS, CSS. , :

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#objectID').css('background', 'transparent url('+e.target.result +') left top no-repeat');
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

- ,

$('#objectID').css('background', 'transparent url('+e.target.result +') left top no-repeat');
+13

All Articles