zoukankan      html  css  js  c++  java
  • js input file选择文件(此处以选择图片为例)

    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] + '" alt=""><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>
  • 相关阅读:
    宝宝咳嗽
    如何查看 oracle 官方文档
    00 序 建立环境
    09 变量重游
    【TYVJ】1359
    【COGS】147. [USACO Jan08] 架设电话线(二分+spfa)
    【wikioi】1904 最小路径覆盖问题(最大流+坑人的题+最小路径覆盖)
    【wikioi】1034 家园(最大流+特殊的技巧)
    【BZOJ】1040: [ZJOI2008]骑士(环套树dp)
    【POJ】2234 Matches Game(博弈论)
  • 原文地址:https://www.cnblogs.com/loya/p/10457196.html
Copyright © 2011-2022 走看看