简体   繁体   English

如何将上传的图片应用于背景图片?

[英]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. 我正在使用标准jQuery上载图像,并且希望将其用作标题的背景图像。 Background-image should receive 'url' and not 'src' attribute, so is it still possible to obtain? Background-image应该接收'url'而不是'src'属性,所以仍然可以获得吗?

jQuery code: jQuery代码:

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. #home-section是赋予标题的ID。 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? 我知道我也可以使用常规的img标签,然后仅使用z-indexes使其功能像背景图像,但这是唯一的选择吗?

Simply wrap the result Data-URL in a url() function for the CSS. 只需将结果Data-URL包装在CSS的url()函数中。 Also use style as attribute name: 也可以使用style作为属性名称:

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

A better approach however is to use the File object (Blob) with Object-URL. 但是,更好的方法是将File对象(Blob)与Object-URL一起使用。 This is faster and leaves a smaller memory footprint. 这样速度更快,并且占用的内存更少。 And as a bonus you can drop the Filereader altogether: 另外,您可以完全删除Filereader

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> 

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

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