美文网首页
HTML file input 选择图片后实时预览

HTML file input 选择图片后实时预览

作者: 无敌的攻城狮 | 来源:发表于2018-06-06 10:57 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>file input 选择图片实时预览</title>
    
      <script type="text/javascript">  
        function getFileObject(sourceId) {
          if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox  
            return window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
          } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome  
            return window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
          } else {
            return document.getElementById(sourceId).value;
          }
        }
    
        function preImg(sourceId, targetId) {
          document.getElementById(targetId).src = getFileObject(sourceId);
        }   
      </script>
    
    </head>
    
    <body>
      <div>
        <form action="">
          <input id="imgFile" type="file" accept="image/*" onchange="preImg(this.id,'photo');" style="display:none" />
          <img id="photo" onclick="document.querySelector('#imgFile').click();" src="默认图片" alt="上传头像" width="300px" height="300px"
          />
        </form>
      </div>
    </body>
    
    </html>
    

    相关文章

      网友评论

          本文标题:HTML file input 选择图片后实时预览

          本文链接:https://www.haomeiwen.com/subject/shfbsftx.html