首页 > Web开发 > 详细

js input file选择文件(此处以选择图片为例)

时间:2019-06-18 17:20:29      阅读:154      评论:0      收藏:0      [点我收藏+]

window.URL.createObjectURL    

可以用于在浏览器上预览本地图片或者视频。以图片为例,生成url

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>test</title>
  <style>
    *{
      list-style: none;
    }
    .img-item {
      position: relative;
     vertical-align: middle;
     width: 100px;
     height: auto;
     float: left;
    }
    .img-item  img{
      display: inline-block;
      width: 100%;
    }
  .close {
    position: absolute;
    right: 0;
    top:-5px;
    width: 20px;
    height: 20px;
  }
  </style>
</head>

<body>
  <input type="file" id=‘check‘ multiple>
  <!--multiple属性可以选择多张  -->
  <ul id=‘imgCon‘></ul>
</body>

</html>
<script>
  var con = document.getElementById(check)
  var imgList = [] // 显示的图片
  con.onchange = function () {
    handleFile(con.files)
    // console.table(con.files)
  }

  function handleFile(files) {
    if (files.length + imgList.length > 4) {
      alert(最多4张) // 最多只能选四张,当前选中的和已显示之和不能大于4
      return
    }
    if (files[0]) {
      for (var i = 0; i < files.length; i++) {
        var img = window.URL.createObjectURL(files[i]) // 将文件生成url
        imgList.push(img)
      }
      show(imgList)
    }
  }

  function show(imgList) {
    var imgCon = document.getElementById(imgCon)
    var html = ‘‘
    for (var i = 0; i < imgList.length; i++) {
      html += <li class="img-item"><img src=" + imgList[i] + " ><span class="close" onclick="delImg( + i +
        )">X</span></li>
    }
    imgCon.innerHTML = html
  }

  function delImg(index) { // 删除显示的图片
    console.log(con.files)
    imgList.splice(index, 1)
    show(imgList)
  }
</script>

 

js input file选择文件(此处以选择图片为例)

原文:https://www.cnblogs.com/loya/p/10457196.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!