jq实现上传头像并实时预览功能


效果

 

 

页面结构

 <form action="" name="form0" id="form0">  
        <input type="file" name="pic" id="pic" class="file0"/>  
        <a href="">选择图像</a>  
        <span id="info"></span>  
        <img src="" alt="" id="img0" width="100" />  
    </form>  

JS代码

 $(function(){  
            $("#pic").change(function(){  
                if($.browser.msie){  
                    $("#img0").attr("src",$(this).val())  
                    $("#info").text("当前选择的文件:"+$(this).val())  
                }else{  
                    $("#info").text("当前选择的文件:"+$(this).val())  
                    var objUrl=getObjectURL(this.files[0]);  
                    console.log("objUrl="+objUrl);  
                    if(objUrl){  
                        $("#img0").attr("src",objUrl);  
                    }  
                }  
            })  
            //建立一個可存取到該file的url  
            function getObjectURL(file) {  
                var url = null ;   
                if (window.createObjectURL!=undefined) {  
                    url = window.createObjectURL(file) ;  
                } else if (window.URL!=undefined) {   
                    url = window.URL.createObjectURL(file) ;  
                } else if (window.webkitURL!=undefined) {   
                    url = window.webkitURL.createObjectURL(file) ;  
                }  
                return url ;  
            }  
        })  

需要注意的是如果使用jQuery 1.9及以上版本移除了$.browser可以使用$.support来替代


免责声明!

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



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