【问题标题】:Get an image to upload and display within a div获取要上传并在 div 中显示的图像
【发布时间】:2014-09-09 21:08:43
【问题描述】:

请查看我的Fiddle...

我有一个文件上传按钮,效果很好。当您几乎不向下滚动小提琴时,您会看到它。图片上传了,但它在页面底部向下上传,我试图让它显示在一个 div 中,就在上传按钮的正下方。

HTML...

`<input type='file' onchange="readURL(this);" /></label>
   <p>
      <strong>(Image will display below)</strong>
   </p>
      <div style="max-width: 100px; height: 100px; border:1px dashed black;">
   <img id="blah" src="#" alt="Your image goes here..." />
</div>`

JS...

`$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});`

【问题讨论】:

    标签: javascript jquery html css image-uploading


    【解决方案1】:

    您使用的是after,它将您的图像插入到input 标记之后,而不是图像。

    要将您的图片插入到您的div 中,您需要在此div 上有一个选择器,例如 id:

    <input type='file' onchange="readURL(this);" /></label>
    <p>
       <strong>(Image will display below)</strong>
    </p>
    <div style="max-width: 100px; height: 100px; border:1px dashed black;" id="whatever">
    </div>
    

    然后做:

    $('#whatever").html(img);
    

    【讨论】:

    • 我也在考虑你的……你确实意识到你的行不通,对吧? fiddle
    • 哦,我忘了先测试它对不起。无论如何,亚当的解决方案更好。
    【解决方案2】:

    更改 div 中已有图像的 src 属性。下面的代码应该做你想做的事。

    `$("input").change(function(e) {
    
        for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
    
            var file = e.originalEvent.srcElement.files[i];
    
            var reader = new FileReader();
            reader.onloadend = function() {
                 $('#blah').attr('src', reader.result);
            }
            reader.readAsDataURL(file);        }
    });`
    

    【讨论】:

    • 给你的问题...知道如何向其中添加多个图像吗?在页面上的不同上传位置?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多