我只是想上传或类似浏览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>
答案 0 :(得分:6)
$(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();
});
});
&#13;
.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;
}
&#13;
<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/*"/>
&#13;
此代码段特定于指定此类accept="image/*"/
答案 1 :(得分:2)
您只需将输入放在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;
}
&#13;
<form id="test_form" method="GET" action="">
<label id="pic1">
Upload Picture
<input type="file" name="fileToUpload" id="fileToUpload" size="1" />
</label>
</form>
&#13;
答案 2 :(得分:0)
<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>