關於利用input的file屬性在頁面添加圖片的問題


在頁面添加圖片涉及到兼容的問題怎么解決兼容問題呢?請看下面分析:

在IE瀏覽器上面我們能直接通過獲取其input的value值來獲取其圖片的路徑。

在火狐和谷歌需要用createObjectURL((input的元素).files.item(0))來獲取其路徑;

現在請看代碼:

css設置樣式部分(可以自己設置好看的樣式):

        *{
            margin: 0;
            padding:0;
        }
        #img{
            width:50px;
        }
        .box{
            width: 100px;
            margin:20px auto;
        }
        .box span{
            width:50px;
            height:50px;
            display: block;
            border-radius:50%;
            overflow:hidden;
            margin:auto;
        }
        .box span img{
            width: 100%;
        }
        .Infor_file{
            position: relative;
            margin-top:20px;
        }
        .Infor_file p{
            width:100px;
            height: 40px;
            text-align: center;
            line-height:40px;
            background:#E77B77;
            color:#fff;
            font-size:16px;
            border-radius:5px;
        }
        #file{
            width:100px;
            height:40px;
            position: absolute;
            top: 0;
            left: 0;
            opacity:0;
            filter:alpha(opacity=0);
        }

html部分:

<div class="box">
    <span><img id="img" src=""/></span>
    <div class="Infor_file"> 
        <p>添加圖片</p> 
     <input type="file" id="file" onchange="get(this)"/> </div> </div>

 js部分:

     var img=document.getElementById("img")
        function get(node){
            var userAgent=navigator.userAgent;
            //適用谷歌和火狐的瀏覽器傳入路徑
            if(userAgent.indexOf("Chrome")!=-1||userAgent.indexOf("Firefox")!=-1){
                img.src=window.URL.createObjectURL(node.files.item(0));
            }
            //適用IE瀏覽器傳入路徑
            if(userAgent.indexOf("MSIE")!=-1){
                img.src=node.value;
            }
        }

以上代碼僅供參考!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM