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

2018-06-06  本文已影响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>
上一篇下一篇

猜你喜欢

热点阅读