javascript - 使用“选择文件”输入来更改 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>
控制台给我“找不到文件”错误。
解决方案
使用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>
推荐阅读
- reactjs - React-Redux 产生 TypeError 无法读取未定义的属性
- app-inventor - AppInventor - 一行列表中的三个值
- pandas - 将小时数添加到格式化为字符串的时间戳
- php - PHP 警告: implode(): 传递的参数无效错误
- typescript - Firebase Firestore,当必须以编程方式解决子字段名称时,如何更新嵌套在子字段中的数组?
- php - 关联账户的条纹退款
- asp.net-core - 从 .net 核心中的像素值保存文件
- pyspark - Delta Lake 合并不更新模式(启用自动模式演变)
- verilog - 如何使用编译器指令 (`ifdef) 和不同的`define's 编译文件?
- r - 使用 Google 字体生成投影仪 PDF 的问题