【问题标题】:Image thumbnail not working图像缩略图不起作用
【发布时间】:2014-10-28 00:02:41
【问题描述】:

我希望当用户上传图片时,他应该能够在图片上传到服务器之前看到它的缩略图。因此,我一直在尝试来自 here 的这个简单的缩略图,但它根本不起作用。

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>  
  <style>
  #imagePreview {
width: 180px;
height: 180px;
background-position: center center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}
</style>
 <script type="text/javascript">
 $(function() {
$("#uploadFile").on("change", function()
{
    var files = !!this.files ? this.files : [];
    if (!files.length || !window.FileReader) return; // no file selected,

    if (/^image/.test( files[0].type)){ // only image file
        var reader = new FileReader(); // instance of the FileReader
        reader.readAsDataURL(files[0]); // read the local file

        reader.onloadend = function(){ // set image data as background of div
            $("#imagePreview").css("background-image", "url("+this.result+")");
        }
    }
    });
 });
   </script>

    <div id="imagePreview"></div>
        <input id="uploadFile" type="file" name="image" class="img" />

【问题讨论】:

  • 你需要更具体地说明你想要什么、你尝试了什么以及问题是什么。
  • 编辑了我想要的@Baszz
  • 您遇到了什么错误?如果有的话?或者你的代码有什么问题?

标签: jquery thumbnails


【解决方案1】:

非常适合我:

HTML:

<div id="imagePreview"></div>
<input id="uploadFile" type="file" name="image" class="img" />

CSS:

#imagePreview {
    width: 180px;
    height: 180px;
    background-position: center center;
    background-size: cover;
    -webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
    display: inline-block;
}

Javascript(你需要 jquery):

$(function() {
    $("#uploadFile").on("change", function()
    {
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support

        if (/^image/.test( files[0].type)){ // only image file
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(files[0]); // read the local file

            reader.onloadend = function(){ // set image data as background of div
                $("#imagePreview").css("background-image", "url("+this.result+")");
            }
        }
    });
});

jsfiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-12
    • 2014-10-13
    • 2014-05-28
    • 2017-05-07
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    相关资源
    最近更新 更多