简体   繁体   中英

change background-image to image file in html 5

I'm using html5 for drag and drop image, my code is still running normally. But, i can only drop image to background-image in dropbox, not image file. So, i can't get and insert image into database. This is my code:

script

    var holder = document.getElementById('leftbox'), state = document.getElementById('status');   
    if ( typeof window.FileReader === 'undefined') {
        state.className = 'fail';
    } else {
        state.className = 'success';
        state.innerHTML = 'Drop files here'
    }

    holder.ondragover = function() {
        this.className = '';
        return false;
    };
    holder.ondragend = function() {
        this.className = '';
        return false;
    };
    holder.ondrop = function(e) {
        this.className = '';
        e.preventDefault();

        var file = e.dataTransfer.files[0], reader = new FileReader();
        reader.onload = function(event) {
            console.log(event.target);
            holder.style.background = 'url(' + event.target.result + ') no-repeat center';
        };
        console.log(file);
        reader.readAsDataURL(file);    
        return false;
    }; 

HTML

<div class="medium-4 medium-centered columns">
        <p id="status"></p>
        <div id="leftbox"></div>
    </div>

What should i do to change holder.style.background to image file? please help me :)

This should help you:

javascript onClick change background picture of div

$('#clickMe').on('click', function() { $('#changeMe').css('background-image', 'url(http://placehold.it/200x200/ff0000)'); })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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