【问题标题】:How update a src of Image如何更新图像的 src
【发布时间】:2020-05-18 22:45:04
【问题描述】:

在我的个人资料中,我插入了一个从电脑加载图片的按钮,但我不知道如何使用用户选择的新图像升级默认用户的图像。然后,当src 中有用户加载的图像时,我想将按钮的文本从 carica 更改为 elima。

function changeImage(){

    var elem = document.getElementById("change_image_button");

    //Se devo caricare l'immagine
    if(elem.value=="Carica"){
        var input = document.createElement('input');
        input.type = 'file';
        input.onchange = e => { 
            var file = e.target.files[0]; 
            var reader = new FileReader();
            reader.readAsDataURL(file,'UTF-8');
            reader.onload = readerEvent => {
                var content = readerEvent.target.result; //File da caricare
                document.getElementById("profilePicture").src= content.src;
            }
        }
        input.click();
        elem.value = "Elimina";
    }

而html代码是:

<!--<Profile picture>-->
                        <img id="profilePicture" src="images/profilo.png" style="height: 173px;width: 160px;margin-left: 20%;margin-top: 20px;">
        <div id="infoLoginUtente">
            <p><span>Cambia Immagine: </span>
            <span> 
               <button onClick="changeImage();" id="change_image_button" value="Carica"> Carica</button> 
               <input id="file-input" type="file" name="name" style="display: none;" />
            </span></p>
        </div>    

坎比亚想象: 卡里卡

但是当我尝试放置图像时,结果是:

【问题讨论】:

  • 用id="profilePicture"看不到元素
  • 是的,抱歉,现在有
  • 也许吧,但我不太了解那个问题中的代码
  • 嗯,一件奇怪的事情是你在一个可能是图像文件的文件上使用readAsText。图像文件通常不是文本文件(SVG 除外,但即使是那些可以作为图像二进制处理的文件)。

标签: javascript html


【解决方案1】:

像这样修改你的input.onchange:

input.onchange = e => { 
  var file = e.target.files[0];             
  document.getElementById("profilePicture").src= URL.createObjectURL(file);
}

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 2012-10-27
    • 1970-01-01
    • 2014-10-24
    • 2014-04-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多