js实现图片上传时本地预览(支持同时上传多张图片)

最近学前端的时候,有个搭建网站的学习任务。其中就有一个功能要实现:可以从本地上传图片到网页,并在本地实现预览。
查了很多资料,最后终于找到一种比较简单的实现方法。

<html>
<head>
    <style>
    .picture{
          width: 600px;
          height: 600px;
          margin-left: 150px;
          border:1px solid #000;
      }
      #img_span img{
          width: 100px;
          height: 100px;
          margin-right: 20px;
          margin-top: 20px;

      }
    </style>
</head>
<body>
     <div class="picture">
            <span id="img_span">
                 <input id="file" class="filepath" onchange="changepic(this)" type="file"><br> 
            </span>
     </div>
</body>
<script>
        var i=0;
        function changepic(obj) {
            //首先插入一个图片标签,src属性为空,宽高设置为100px,暂时设为不可见
            document.getElementById("img_span").innerHTML+="<img src=\"\" id=\"show"+i+"\" width=\"200\" style=\"opacity: 0;\">"; 
            //调用getObjectURL函数,返回上传的图片的地址
            var newsrc=getObjectURL(obj.files[0]);
            document.getElementById('show'+i).src=newsrc;//将图片的路径设置为返回上传的图片的地址
            document.getElementById("show"+i).style.opacity=1;//将图片设置为可见
            i++;
        }
        //建立一个可存取到该file的url
        function getObjectURL(file) {
            var url = null ;
            // 下面函数执行的效果是一样的,只是需要针对不同的浏览器执行不同的 js 函数而已
            if (window.createObjectURL!=undefined) { // basic
                url = window.createObjectURL(file) ;
            } else if (window.URL!=undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file) ;
            } else if (window.webkitURL!=undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file) ;
            }
            return url ;
        }
    </script>
</html>

运行截图:
在这里插入图片描述
暂时没有解决的问题: 上传后的图片不能删除

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值