How to upload image file from computer and set as div background image using jQuery?

后端 未结 3 1983
南旧
南旧 2020-12-28 10:05

The HTML code for image file input:


The des

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 10:53

    It's small way to do this without using FileReader.

    http://jsfiddle.net/PuneetChawla/vqn7r0nj/

    HTML



    CSS

    #clock{
               background-image:url('');
               background-size:cover;
               background-position: center;
               height: 250px; width: 250px;
               border: 1px solid #bbb;
                }
    

    JavaScript

    function readURL(event){
             var getImagePath = URL.createObjectURL(event.target.files[0]);
             $('#clock').css('background-image', 'url(' + getImagePath + ')');
            }
    

    Explanation - The URL.createObjectURL() static method creates a DOMString containing an URL representing the object given in parameter.

提交回复
热议问题