我有一个文件上传元素:
<input type="file" name='image1' id='image1'>
然后我有一个按钮:
<button onclick="addphotos()">Add photos</button>
addphotos()函数是:
function addphotos() {
var file1 = document.getElementById('image1').files[0];
var img1=file1.name.split(/(\\|\/)/g).pop();
var pic1 = "url(" + file1 + ")";
document.getElementById("right").style.backgroundImage=pic1;
}
据我所知,最后一行的语法应该是正确的,但我想我错过了一些东西。最后一行语法参考 - http://www.w3schools.com/cssref/tryit.asp?filename=trycss_js_background-image
编辑:它无法正常工作。没有任何图像放在立方体的脸上。答案 0 :(得分:1)
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('input');
var container = document.getElementById('image-block');
function onFilePicked(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var image = event.target.result;
container.style.backgroundImage = 'url(' + image + ')';
};
reader.readAsDataURL(file);
}
input.addEventListener('change', onFilePicked);
});
&#13;
#image-block {
width: 100px;
height: 100px;
}
&#13;
<input type="file" id="input">
<div id="image-block"></div>
&#13;