主要就是运用URL.createObjectURL()方法创建临时的图片地址
<!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>
</head>
<body>
<div>头像:<input type="file" onChange="fileChange()" id="file"></div>
<img src="" alt="">
<script>
function fileChange(){
var file=document.querySelector('#file').files[0];
document.querySelector('img').src=URL.createObjectURL(file)
}
</script>
</body>
</html>
有时候觉得选择文件的input框太丑,那么我们就隐藏用其他元素来代替,主要就是替换元素的点击事件触发input的点击事件
<!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>
</head>
<body>
<div>头像:<input type="file" onChange="fileChange()" id="file"> <span onclick="uploadImg()"></span> </div>
<img src="" alt="" id="img">
<script>
function fileChange(){
var file=document.querySelector('#file').files[0];
document.querySelector('#img').src=URL.createObjectURL(file)
}
function uploadImg(){
document.querySelector('#file').click();//触发input的点击事件即可
}
</script>
<style>
div span{display: inline-block;width: 30px;height: 30px;background: #ccc;border-radius: 6px;cursor: pointer;}
input{display: none}
</style>
</body>
</html>