jquery - 自定义上传按钮作为图片预览

标签 jquery html css file-upload

我正在使用以下代码来显示图像预览。在下面的代码中,图像预览和选择按钮是分开的,但我希望它们都像下图一样: enter image description here

如上图所示,首先显示的是添加按钮。然后,一旦选择了图像,它就会显示预览。

这是我使用的代码:

HTML

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

脚本

<script type="text/javascript">
$(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+")");
            }
        }
    });
});
</script>

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;
}

最佳答案

  1. 隐藏输入
  2. .onclick() 附加到图像占位符
  3. 手动触发输入点击

$(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+")");
            }
        }
    });
});

$('#imagePreview').click(function(){
  $('#uploadFile').click();
});
#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;
    background-image: url('http://via.placeholder.com/350x150');
}

#uploadFile{
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imagePreview" src="http://via.placeholder.com/350x150" alt="placeholder image goes here"></div>
<input id="uploadFile" type="file" name="image" class="img" />

关于jquery - 自定义上传按钮作为图片预览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49857040/

相关文章:

javascript - 为标签内容添加漂亮的滑动效果

jQuery Ui 对话框按钮,如何添加类?

JQuery 日期范围 : How to trigger an init "selection" event to set default values

javascript - handlebars #每个数组都是助手

html - 适合 A4 尺寸的 html 表格

javascript - chrome.alarms api 无法与 angularJS 正常工作

javascript - 重构js以编程方式在div中附加内容

html - 如何使页脚有固定的位置

javascript - 带有 onLeave 和 afterLoad 的 fullpage.js 动画

css - 试图覆盖 CSS wordpress 默认的白色粗体颜色