我使用以下代码显示图像预览。在下面的代码中,图像预览和选择按钮是分开的,但我希望它们都像下面的图像一样:
如上图所示,首先显示添加按钮。然后,一旦选择了图像,它就会显示预览。
以下是我使用的代码:
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;
}
答案 0 :(得分:1)
您可以使用<label>
来表示和装饰input
。
这是一个简单的演示:
$('#file1').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
$('img').attr('src', reader.result).removeClass('default')
}
}
})
&#13;
#file1 {
display: none;
}
img {
cursor: pointer;
width: 200px;
height: 200px;
}
img.default {
border: 2px gray dashed;
padding: 50px;
height: 150px;
width: 150px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file1">
<label for="file1">
<img src="https://cdn3.iconfinder.com/data/icons/iconic-1/32/plus_alt-256.png" class="default" alt="">
</label>
&#13;
答案 1 :(得分:0)
response = bucket_tagging.put(
Tagging={
'TagSet': [
{
'Key': 'string',
'Value': 'string'
},
]
}
)
附加到图片占位符HIH
.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
}