<!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;
}
.file-box{
margin: 20px auto;
border: 1px solid #ccc;
width: 600px;
padding: 12px 12px 12px 18px;
}
.file-box .load{
position: relative;
}
.file-box .load #file{
width: 32px;
height: 32px;
opacity: 0;
position: absolute;
left: 0;
top: 0;
cursor: pointer;
}
.file-box .load img{
width: 32px;
height: 32px;
}
.file-box .load button{
float: right;
width: 60px;
height: 32px;
line-height: 32px;
text-align: center;
color: #fff;
background: mediumpurple;
outline: none;
border: none;
border-radius: 4px;
cursor: pointer;
}
.load-show{
margin-top: 10px;
border: 1px solid;
width: 100%;
height: auto;
}
.load-show img{
width: 200px;
height: 200px;
padding: 20px;
}
</style>
</head>
<body>
<div class="file-box">
<div class="load">
<input type="file" id="file"/>
<img src="img/load.png" />
<button type="button">发送</button>
</div>
<div class="load-show">
</div>
</div>
<script>
//获取文件url
function createObjectURL(blob) {
if(window.URL) {
return window.URL.createObjectURL(blob);
} else if(window.webkitURL) {
return window.webkitURL.createObjectURL(blob);
} else {
return null;
}
}
var show = document.querySelector(".load-show"); //显示图片box
var file = document.querySelector("#file"); //file对象
var domFragment = document.createDocumentFragment(); //文档流优化多次改动dom
//触发选中文件事件
file.onchange = function(e) {
// show.innerHTML = ""; //清空上一次显示图片效果,只能单张图设置
e = e || event;
var file = this.files; //获取选中的文件对象
for(var i = 0, len = file.length; i < len; i++) {
var imgTag = document.createElement("img");
var fileName = file[i].name; //获取当前文件的文件名
var url = createObjectURL(file[i]); //获取当前文件对象的URL
//忽略大小写
var jpg = (fileName.indexOf(".jpg") > -1) || (fileName.toLowerCase().indexOf(".jpg") > -1);
var png = (fileName.indexOf(".png") > -1) || (fileName.toLowerCase().indexOf(".png") > -1);
var jpeg = (fileName.indexOf(".jpeg") > -1) || (fileName.toLowerCase().indexOf(".jpeg") > -1);
//判断文件是否是图片类型
if(jpg || png || jpeg) {
imgTag.src = url;
domFragment.appendChild(imgTag);
} else {
alert("请选择图片类型文件!");
}
}
//最佳显示
show.appendChild(domFragment);
}
</script>
</body>
</html>