我有一个“按钮”(一个类似于按钮的 anchor )。您可以在哪里上传预览的图片。
但我想做的是让上传的图片显示而不是按钮(相同大小等)。有什么好的方法吗?
$(document).ready(function() {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (event) {
$('#imageChosen').attr('src', event.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$('#fileInput').change(function(){
readURL(this);
});
});
div.input {
border-style: solid;
border-width: 5px;
display: inline-block;
}
#filebutton {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>for testing</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/costum.js"></script>
<link rel="stylesheet" type="text/css" href="css/costum.css">
</head>
<body>
<div class="input">
<label for="fileInput">
<input type="file" id="fileInput" style="display: none;" />
<a style="display: block;" type="button" id="filebutton">Upload</a>
<img id="imageChosen">
</label>
</div>
</body>
</html>
最佳答案
如何通过 $('div.input').css('background-image', 'url(' + event.target.result + ')') 将图像用作背景
?
然后您可能希望将 background-size
设置为 cover
或 contain
。
示例:
$(document).ready(function() {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(event) {
$('div.input').css('background-image', 'url(' + event.target.result + ')');
}
reader.readAsDataURL(input.files[0]);
}
}
$('#fileInput').change(function() {
readURL(this);
});
});
div.input {
border-style: solid;
border-width: 5px;
display: inline-block;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
#filebutton {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input">
<label for="fileInput">
<input type="file" id="fileInput" style="display: none;" />
<a style="display: block;" type="button" id="filebutton">Upload</a>
</label>
</div>
关于javascript - 显示上传的图片而不是上传按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43437563/