我只是想上传或浏览div本身,就像作为文件输入并触发其功能,但我的问题是我对java脚本很陌生,并且为自己集思广益了近一个小时并寻找互联网上同样的问题。
所以我别无选择只能在这里提问
我的代码
<script type="">
$('#pic1').click(function (Upload) {
$('#fileToUpload').click();
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="pic1" style="border:1px solid white;width:200px;height:150px;float:left;margin:10px;" onclick="Upload">
<input type="file" name="fileToUpload" id="fileToUpload" size="1" style="display:none;">
</div>
<br> while my file input is hidden inside the div<br>
$(document).ready(function() {
var readURL = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.profile-pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".file-upload").on('change', function(){
readURL(this);
});
$(".upload-button").on('click', function() {
$(".file-upload").click();
});
});
.upload-button {
padding: 4px;
border: 1px solid black;
border-radius: 5px;
display: block;
float: left;
}
.profile-pic {
max-width: 200px;
max-height: 200px;
display: block;
}
.file-upload {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="profile-pic" src="http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg" />
<div class="upload-button">Upload Image</div>
<input class="file-upload" type="file" accept="image/*"/>
此代码片段特定于这样指定的图像
accept="image/*"/
您只需将输入包装在
label
内即可。
尝试以下代码。
input[type=file] {
display: none;
}
label {
border: 1px solid white;
text-align: center;
color: #FFF;
border-radius: 4px;
margin: auto;
width: 120px;
padding: 10px;
display: block;
background-color: #0095ff;
cursor: pointer;
}
<form id="test_form" method="GET" action="">
<label id="pic1">
Upload Picture
<input type="file" name="fileToUpload" id="fileToUpload" size="1" />
</label>
</form>
<style type="text/css">
#pic1{
border:1px solid black;
width:200px;
height:150px;
}
</style>
<form action="" method="post" enctype="multipart/form-data">
<div id="pic1">Upload</div>
<input type="file" name="fileToUpload" id="fileToUpload" style="display:none;"/>
<input type="submit" value="submit" name="submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$('#pic1').click(function(){
$('#fileToUpload').trigger('click');
});
</script>