【问题标题】:How to apply an uploaded image to a background-image?如何将上传的图像应用到背景图像?
【发布时间】:2018-09-01 13:15:43
【问题描述】:

我正在使用标准 jQuery 上传图片,我希望它可以用作标题的背景图片。 background-image 应该接收 'url' 而不是 'src' 属性,所以仍然可以获得吗?

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 是标题的 id。我知道我也可以使用常规的 img 标签,然后使用 z-indexes 使其像背景图像一样发挥作用,但这是唯一的选择吗?

【问题讨论】:

    标签: javascript jquery background-image filereader


    【解决方案1】:

    只需将结果 Data-URL 包装在 CSS 的 url() 函数中。同样使用style作为属性名:

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

    然而,更好的方法是将文件对象 (Blob) 与 Object-URL 一起使用。这更快并且留下更小的内存占用。作为奖励,您可以完全放弃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>

    【讨论】:

    • 嘿 Epistemex 非常感谢,非常有帮助,很高兴了解这种更好的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2011-01-03
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多