圖片上傳預覽效果程式碼例項

admin發表於2017-04-16

分享一段程式碼例項,它實現了上傳圖片預覽效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#click {
  width: 200px; 
  height: 200px; 
  border: 1px solid #000;
}
</style>
</head>
<body>
<input type="file" id="photo">
<div id="click"></div>
<script>
document.getElementById('photo').addEventListener('change', function(e) {
  var files = this.files;
  var img = new Image();
  var reader = new FileReader();
  reader.readAsDataURL(files[0]);
  reader.onload = function(e) {
    var mb = (e.total / 1024) / 1024;
    if (mb >= 2) {
      alert('檔案大小大於2M');
      return;
    }
    img.src = this.result;
    img.style.width = "80%";
    document.getElementById('click').style.width = "200px";
    document.getElementById('click').style.height = "200px";
    document.getElementById('click').innerHTML = '';
    document.getElementById('click').appendChild(img);
  }
});
</script>
</body>
</html>

相關文章