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