JS--前端input多选上传图片功能


1.引入Jquery文件
2.样式

.imgbox {
    float: left;
    position: relative;
    width: 100px;
    height: 100px;
    margin-left: 10px;
    margin-top: 10px;
    padding: 5px;
    border: solid 1px red;
    border-radius: 5px;	
}
.imgbox .close{
    background: rgba(255,255,255,.5);
    width: 100px;
    height: 100px;
    position: absolute;
    top: 5px;
    text-align: center;
    line-height: 150px;
    color: red;
    display: none;
}
.imgbox input {
    width: 100%;
    height: 100%;
    z-index: 10;
}

注意: multiple="multiple" 多选属性 accept="image/*" 为图片格式,要和 type="file" 一起使用

<input type="file" onchange="load(this)" multiple="multiple" accept="image/*" class='myfile'></input>
<div id="view"></div>
//移入显示删除按钮,移出正常显示图片
$('body').on('mouseover', '.imgbox', function() {
    console.log('1')
    $(this).children('div').css("display","block");
});
$('body').on('mouseout', '.imgbox', function() {
    $(this).children('div').css("display","none");
});
//点击删除当前选中的图片
$('body').on('click', '.close', function() {
    $(this).parent('.imgbox').remove();
});
//上传图片
function load(file) {
    var num = 1;
    if (file.files) {
        for (var i = 0; i < file.files.length; i++) {
            var reader = new FileReader();
            reader.readAsDataURL(file.files[i]);
            reader.onload = function(evt) {
                var imgbox = $('<div></div>');
                imgbox.addClass('imgbox');
                $('#view').append(imgbox);

                var close = $('<div>删除</div>');
                close.addClass('close');
                close.appendTo(imgbox);

                var imgs = $('<input type="image" />');
                imgs.attr('name', 'mum' + num);
                num++;
                imgs.appendTo(imgbox);
                imgs.attr('src', evt.target.result);
            }
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM