创建HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div id="submit_area" οnclick="submit()">+上传图片 </div>
<input id="submit_img" type="file" style="display: none" οnchange="preview(this)">
</body>
</html>
编写CSS
#submit_area{
width:240px;
height:135px;
background-color: #f3f5f4;
text-align: center; //文字内容水平居中
margin-top: 20px;
line-height: 135px;//行高和height设置一样时 ,可以垂直居中
margin-left: 100px;
cursor:pointer; //鼠标划入区域时编程小手
}
编写js
function submit(){
document.getElementById('submit_img').click() //触发被设置为none的input
}
function preview(e){
const windowUrl=window.URL||window.webkitURL||window.mozURL;//适配不同浏览器
if(e.files[0]){
const imgURL = windowUrl.createObjectURL(e.files[0]);
document.getElementById('submit_area').style.backgroundImage="url("+imgURL+")";
}
}
低版本浏览器不支持URL.createObjectURL() ,生成的URL对象会占用大量资源,在不用时可用用URL.RevokeObjectURL(),及时删除。