【问题标题】:How to display an image which i inputted如何显示我输入的图像
【发布时间】:2020-12-31 23:12:45
【问题描述】:

我制作了一个将图像作为输入的按钮,但我找不到显示图片的方法。 我试图创建一个空元素,然后像在其他网站上看到的那样更改其 URL,但它没有用。

  • HTML

     <input 
         id="myImage"
         class="photo-upload"
         type="file"
         accept="image/*, image/jpeg">
    
         <img id="the-picture" width="200" />
    
  • JavaScript

     const uploadPictureButton = document.querySelector(".photo-upload");
    
     uploadPictureButton.addEventListener("click", displayPicture);
    
     function displayPicture(event) {
         let image = document.getElementById("myImage");
         image.src = URL.createObjectURL(event.target.files[0]);
     };
    

【问题讨论】:

标签: javascript image input display


【解决方案1】:

代码中需要一些修复,必须读取文件并创建 URL,这是代码的工作 sn-p。

const uploadPictureButton = document.querySelector(".photo-upload");

  uploadPictureButton.addEventListener('change', function () {
    displayPicture(this);
  });

 function displayPicture(input) {
    if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      document.getElementById('the-picture').setAttribute('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
 }
 <input 
     id="myImage"
     class="photo-upload"
     type="file"
     accept="image/*, image/jpeg">

<img id="the-picture" width="200" /> 

【讨论】:

  • 我尝试运行它,效果很好!但我真的不明白为什么,你能解释一下你为什么这样做:if(uploadPictureButton) 而不是直接进入函数?
  • 我删除了,这里不需要,谢谢指出!
【解决方案2】:

试试这个,它对我有用

&lt;img height="100" width="100" alt="avatar" id="imgPreview&gt; &lt;input type="file" onchange="document.querySelector("#imgPreview").src = window.URL.createObjectURL(this.files[0])"&gt;

【讨论】:

    【解决方案3】:

    您也可以使用innerHTML 显示图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      相关资源
      最近更新 更多