简体   繁体   中英

How to apply an uploaded image to a background-image?

I'm using standard jQuery to upload an image, and I would like it to apply as the background image of the header. Background-image should receive 'url' and not 'src' attribute, so is it still possible to obtain?

jQuery code:

function uploadImage(input){
    if (input.files && input.files[0]) {
     var reader = new FileReader();
     reader.onload = function(e) {
         $('#home-section').attr('background-image...???', e.target.result);
     }
     reader.readAsDataURL(input.files[0]);
    }
}

#home-section is the id given to the header. I know I also can use a regular img tag and then just play with z-indexes to make it function like a background image, but is that the only option?

Simply wrap the result Data-URL in a url() function for the CSS. Also use style as attribute name:

$('#home-section').attr('style', 'background-image:url(' + e.target.result + ')');

A better approach however is to use the File object (Blob) with Object-URL. This is faster and leaves a smaller memory footprint. And as a bonus you can drop the Filereader altogether:

function uploadImage(input){
  if (input.files && input.files[0]) {
    var url = URL.createObjectURL(input.files[0]);
    $('#home-section').attr('style', 'background-image:url(' + url + ')');
  }
}

 function uploadImage(input){ if (input.files && input.files[0]) { var url = URL.createObjectURL(input.files[0]); $('#home-section').attr('style', 'background-image:url(' + url + ')'); } } document.querySelector("input").onchange = function(){uploadImage(this)}; 
 #home-section {width:640px; height:480px} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>Select image: <input type=file></label><br> <div id=home-section></div> 

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