html 自定义上传图片样式,并回显

<div id="photoUpLoad">
     <input type="file" id="photo" name="" accept="image/*"><span class="cross">+</span>
     <img src="" alt="" id="photoEcho">
</div>
#photoUpLoad{
    width: 106px;
    height: 129px;
    position: relative;
    cursor: pointer;
    border-radius: 2px;
    border: solid 1px #d0daea;
}
#photo{
    opacity: 0;
    z-index: 999;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
#photoEcho{
    z-index: 99;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

#photoUpLoad .cross{
    color: #d0daea;
    font-size: 44px;
    line-height: 44px;
    position: absolute;
    top: 38px;
    right: 36px;
}
    $("#photo").change(function(){
        var file = this.files[0];
        console.log(file);
        if(!file){
            return false;
        }

        var maxSize = 1024 ; //图片最大KB
        if(!/(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.type)){
            top.alertLocal("请上传gif,jpeg,jpg,png格式的图片!");
            return;
        }
        if(file.size > maxSize* 1024){
           top.alertLocal("请上传"+maxSize+"KB以下的图片");
           return;
        }

        var objUrl = getObjectURL(file) ;
        if (objUrl) {
            $("#photoEcho").attr("src", objUrl) ;
        }
    }) ;
    //建立一個可存取到該file的url
    function getObjectURL(file) {
        var url = null ;
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    }

猜你喜欢

转载自www.cnblogs.com/zhanglw456/p/10731368.html