网上找各种多图预览上传插件,感觉太麻烦,翻看各种插件文档,用起来都太麻烦了,于是干脆自己动手实现该功能
以下为效果图
废话不多说,直接贴代码
直接复制一下代码即可运行
<!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>多图片上传</title>
<style>
* {
margin: 0;
padding: 0;
}
.upload-img {
position: relative;
margin: 300px;
}
.upload-img .img-box {
position: relative;
float: left;
margin: 0 20px;
border: 1px solid rgb(190, 184, 184);
width: 140px;
height: 140px;
text-align: center;
background: #eee;
}
.upload-img .image-icon {
position: absolute;
left: 50px;
top: 50px;
display: block;
width: 40px;
height: 40px;
}
.upload-img .image-icon:hover {
border: 1px solid blue;
}
.upload-img .upload-file {
z-index:1;
width: 100%;
height: 100%;
opacity: 0;
}
.upload-img .image-path{
position: absolute;
left: 0;
top: 0;
z-index: 9;
width: 140px;
height: 140px;
display: none;
}
.upload-img .close-icon {
z-index: 10;
background: url('./close.png') no-repeat;
background-size: 40px;
position: absolute;
right: -20px;
top: -20px;
width: 40px;
height: 40px;
display: none;
}
.clonebox {
display: none;
}
</style>
<script src="./jquery.min.js"></script>
</head>
<body>
<div class="clonebox">
<i class="close-icon"></i>
<img src="" alt="" class="image-path">
<img src="./upload.png" alt="" class="image-icon">
<input class="upload-file" name="img1[]" type="file">
</div>
<div class="upload-img" id="js-upload-img">
<div class="img-box">
<i class="close-icon"></i>
<img src="" alt="" class="image-path">
<img src="./upload.png" alt="" class="image-icon">
<input class="upload-file" name="img[]" type="file">
</div>
</div>
<script>
$(function () {
$('.upload-file').on('change', function (event) {
var file = event.target.files[0];
var $that = $(this);
if (window.FileReader) {
var reader = new FileReader();
reader.onloadend = function (e) {
var imgFile = e.target.result;
$that.siblings('.image-icon').hide();
$that.siblings('.image-path').show();
$that.siblings('.close-icon').show();
$that.siblings('.image-path').attr({ 'src': imgFile });
if ($('#js-upload-img .img-box').length < 3) {
$('#js-upload-img').append($('.clonebox').clone(true).addClass('img-box').removeClass('clonebox').show());
}
};
//监听文件读取结束后事件
reader.readAsDataURL(file);
}
$(this).val(''); //必须,确保上传相同的文件时能触发
})
$('.close-icon').click(function (e) {
$(this).siblings('.image-path').attr({ src: '' });
$(this).siblings('.image-path').hide();
$(this).hide();
$(this).siblings('.image-icon').show();
})
});
</script>
</body>
</html>