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