关于利用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;
            }
        }

以上代码仅供参考!

原文地址:https://www.cnblogs.com/zouxianlu/p/6536375.html