首页 > 解决方案 > 使用“选择文件”输入来更改 div backgroundImage

问题描述

我正在尝试从他的本地机器上用用户的图片更改 div 背景。但这似乎对我不起作用。

$("#addPhoto").change(function() {
  var fileName = $(this).value;
  $("#myPic").css({
    "backgroundImage": "url('" + fileName + "')"
  });
});
#myPic {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  position: relative;
  bottom: -7%;
  left: -4%;
  background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" accept="image/*" id="addPhoto" />
<div id="myPic"></div>

控制台给我“找不到文件”错误。

标签: javascriptjqueryhtmlcss

解决方案


使用FileReader可以轻松做到这一点:

$("#addPhoto").change(function() {
    var file = this.files[0];
    var reader = new FileReader();
    reader.onloadend = function() {
        $("#myPic").css({
            "background-image": "url('" + reader.result + "')"
        });
    }
    if (file) {
        reader.readAsDataURL(file);
    } else {}
});
#myPic {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  position: relative;
  bottom: -7%;
  left: -4%;
  background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" accept="image/*" id="addPhoto" />
<div id="myPic"></div>


推荐阅读