有没有办法更改标签内的src-url?

时间:2019-04-14 09:04:30

标签: javascript

我有一个上传部分,我想在其中上传图片。但是我不想使用标准的上传按钮,因此我带有带有图像的标签。

HTML

  <div class="image-upload">
    <label for="imgInp"><img id="blah" src="https://www.gravatar.com/avatar/9a6676e137fefad07752853bcc656a39?s=48&d=identicon&r=PG&f=1" width="320px" height="240" style="padding-bottom:10px" /></label>
    <input type='file' id="imgInp" />
  </div>

脚本

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

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

css隐藏默认的上传按钮

.image-upload > input {
  display: none;
}

我想做的是更改标签标签中的图片src-url。有什么聪明的方法可以做到这一点?我已经尝试过类似的操作,但是当我用标签将图像预览括起来时,该代码将不再起作用。

1 个答案:

答案 0 :(得分:0)

只有一点错字。 你用过

$('#blah').attr('src', e.target.result);

但是您图片元素的ID等等 h