预览图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
position: relative;
}
span{
display: inline-block;
width:90px;
height: 35px;
border: 1px solid #ccc;
text-align: center;
line-height: 35px;
background-color: red;
}
input[type="file"] {
width: 100px;
height: 40px;
position: absolute;
top: 0;
left: 0;
z-index: 99;
opacity: 0;
}
</style>
</head>
<body>
<form action="">
<span>选择文件</span>
<input type="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"><br>
<img src="" alt="" style="height: 100px;">
</form>
</body>
<script>
var input = document.getElementsByTagName('input')[0];
var img = document.getElementsByTagName('img')[0];
input.onchange = function(){
let fileIcon = this.files[0];
var url = URL.createObjectURL(fileIcon);
img.setAttribute('src',url)
}
</script>
</html>