我正在使用以下代码来显示图像预览。在下面的代码中,图像预览和选择按钮是分开的,但我希望它们都像下图一样:
如上图所示,首先显示的是添加按钮。然后,一旦选择了图像,它就会显示预览。
这是我使用的代码:
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;
}
- 隐藏输入
- 将
.onclick()
附加到图像占位符
- 手动触发输入点击
高
$(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" />
我是一名优秀的程序员,十分优秀!