gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:24 24 4
gpt4 key购买 nike

我正在使用以下代码来显示图像预览。在下面的代码中,图像预览和选择按钮是分开的,但我希望它们都像下图一样: 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com