1. 程式人生 > >jQuery多圖上傳預覽

jQuery多圖上傳預覽

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery多圖上傳預覽</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
.imgFile {
    width:500px;
    border:1px solid #dbdbdb;
    display:flow-root
}
@supports (display:flow-root) {
    .imgFile {
    display:flow-root;
}
}.imgFile label input {
    display:none
}
.imgFile label span {
    width:100px;
    height:100px;
    display:inline-block;
    border:1px solid #999999;
    margin:16px;
    position:relative
}
.imgFile label span:after {
    width:60%;
    height:1px;
    background:#dbdbdb;
    content:"";
    display:inline-block;
    position:absolute;
    top:50%;
    left:calc(50% - 30%)
}
.imgFile label span:before {
    width:1px;
    height:60%;
    background:#dbdbdb;
    content:"";
    display:inline-block;
    position:absolute;
    left:50%;
    top:calc(50% - 30%)
}
.imgFile .imgDiv {
    width:100px;
    height:100px;
    border:1px solid #999999;
    margin:16px;
    position:relative;
    float:left
}
.imgFile .imgDiv img {
    width:100%;
    height:100%;
}
.imgFile .imgDiv span {
    width:100%;
    height:20%;
    color:white;
    display:none;
    background:rgba(0,0,0,0.38);
    position:absolute;
    top:0;
    left:0;
    right:0
}
.imgFile .imgDiv i {
    font-style:inherit;
    float:right;
    cursor:pointer;
    margin-right:5px;
    line-height:100%;
    font-size:20px
}
.imgFile .imgDiv:hover > span {
    display:block
}
</style>
</head>
<body>
<div class="imgFile">
    <label>
        <span></span>
        <input type="file" class="file">
    </label>
</div>

<script>
$(".file").change(function() {
    //獲取圖片資訊
    var fileLise = $(this)[0].files;
    var fileLength = fileLise.length;
    //然後迴圈 生成html 插入頁面上 最後就賦值給img
    for (var i = 0; i < fileLength; i++) {
        var imgDiv = '<div class="imgDiv"><img id="img' + fileLise[i].name + '"><span><i class="imgRem">×</i></span></div>';
        $(".imgFile").prepend(imgDiv);
        var imgName = document.getElementById("img" + fileLise[i].name);
        if (fileLise && fileLise[i]) {
            var file = new FileReader();
            file.readAsDataURL(fileLise[i]);
            file.onload = function() {
                console.log(this);
                imgName.src = this.result
            }
        }
    }
});
$(".imgFile").on("click", ".imgRem", function() {
    $(this).parents(".imgDiv").remove();
});
</script>

</body>
</html>