javascript - 使用 "choose file"输入更改 div backgroundImage

标签 javascript jquery html css

我正在尝试从他的本地计算机更改带有用户图片的 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>

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

最佳答案

使用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>

关于javascript - 使用 "choose file"输入更改 div backgroundImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51055308/

相关文章:

html - css 边框不显示在每个元素的顶部

html - 将图像固定在顶部,但两侧有自动边距

javascript - ajax调用完成后执行函数

javascript - Ajax beforesend 方法在某些情况下不起作用

javascript - jquery post ajax 语法不起作用

javascript - 带有单选按钮的 JSON 到 Html 表

jquery 小部件 css 覆盖了我自己的 css

javascript - 在 React Native 中构建应用程序后出现空白屏幕

javascript - polymer "DOM-Bind"更新绑定(bind)

javascript - 如何在 Javascript/Jquery 中获取包含单击文本的元素?