下面是ES6的写法
下面的图片和input通过定位,让input在img上方,然后将input的opcity设置为1,img设置自己想设置的图片即可
// html 中的input
<div>
<img id="inputImg" src="图片路径">
<input type="file" id="input">
</div>
// script 中的图片上传(ajax)
document.getElementById('input').onclick = function () {
var file = this.file[0];
// 将选择的图片显示到页面中
document.getElementById('inputImg').src = window.URL.createObjectURL(file);
// ajax
var form = new FormData();
form.append('file', file);
var xhr;
if (window.XMLHttpRequeat) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveObject('Microsoft.XMLHTTP');
}
xhr.open('post', 'http://......');
xhr.send(form);
xhr.onreadystatechange = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
var data = xhr.responseText;
var json = JSON.parse(data);
console.log(json);
}
}
}