如何在上传图片后更改 DIV 的背景?

How do I change the background of a DIV after uploading an image?

现在我有一个占位符图像设置为背景,上面有一个不可见的 asp:FileUpload。用户单击并选择图像后,我想更改占位符图像(使用 css 背景设置)。

<div id="icon">
    <asp:FileUpload ID="AvatarUpload" CssClass="avatar-upload" runat="server" size="38" />
</div>

CSS:

#icon {
    width: 120px;
    height: 120px;
    background: url("../image/mobile/upload-avatar.png") no-repeat bottom center;
    background-size: 120px 120px;
}

.avatar-upload {
    opacity: 0;
    width: 100%;
    height: 120px;
    cursor: pointer;
}

有没有不用 submit/upload 按钮的方法?

这应该可以满足您的需求:

    var icon = document.querySelector('#icon');
    document.querySelector('#AvatarUpload').addEventListener("change",function(e){        
       icon.style.background = 'url('+URL.createObjectURL(e.target.files[0])+')';
    });
#icon{
  width : 120px;
  height : 120px;
  background : red;
  background-size: contain ! important;
  overflow : hidden;
 }

#AvatarUpload{
  opacity: 0;
  width: 100%;
  height: 120px;
}
<div id="icon">
  <input type="file" id="AvatarUpload"/>
</div>