码迷,mamicode.com
首页 > 编程语言 > 详细

两种方式javascript实现图片预览

时间:2020-05-16 20:29:03      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:asd   代码   oct   UNC   show   targe   ice   htm   title   

方式一:更适合H5页面,兼容ie10+,图片base64显示,主要功能点是FileReader和readAsDataURL

简洁代码如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>files-h5</title>
</head>
<body>
  <input type="file" id="file" onchange="showPreview(this, ‘portrait‘)" />
  <img src="" id="portrait" style="width: 200px; height: 200px; display: block;" />
  <script>
  function showPreview(source, imgId) {
    var file = source.files[0];
    if(window.FileReader) {
      var fr = new FileReader();
      fr.onloadend = function(e) {
        document.getElementById(imgId).src = e.target.result;
      }
      fr.readAsDataURL(file);
    }
  }
  </script>
</body>
</html>

方式二:更适合PC端,兼容ie7+,主要功能点是window.URL.createObjectURL

简洁代码如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>files-pc</title>
</head>
<body>
  <input type="file" id="file" onchange="showPreview(this.id,‘portrait‘)" />
  <img src="" id="portrait" style="width: 200px; height: 200px; display: block;" />
  <script type="text/javascript">
  /* 图片预览 */
  function showPreview(fileId, imgId) {
    var file = document.getElementById(fileId);
    var ua = navigator.userAgent.toLowerCase();
    var url = ‘‘;
    if(/msie/.test(ua)) {
      url = file.value;
    } else {
      url = window.URL.createObjectURL(file.files[0]);
    }
    document.getElementById(imgId).src = url;
  }
  </script>
</body>
</html>

两种方式javascript实现图片预览

标签:asd   代码   oct   UNC   show   targe   ice   htm   title   

原文地址:https://www.cnblogs.com/baimeishaoxia/p/12901838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!