关于利用input的file属性在页面添加图片的问题

本文介绍了一种在不同浏览器中实现图片上传功能的兼容性方案。针对IE、火狐及谷歌等浏览器,提供了具体的代码实现,确保图片路径的正确获取。

在页面添加图片涉及到兼容的问题怎么解决兼容问题呢?请看下面分析:

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值