Swe*_*wen 1 javascript jquery file-upload input
我正在开发一个拖放文件上传器,可以通过单击标签或将文件拖放到标签上来触发。
输入字段有一个 jQueryon change事件,当选择文件时会触发该事件。但它仅在通过资源管理器菜单选择文件时有效,而在拖放事件中无效。为什么?
$(document).ready(function() {
$('label').on('drag dragstart dragend dragover dragenter dragleave drop', function(event) {
event.preventDefault();
event.stopPropagation();
})
.on('dragover dragenter', function() {
$(this).addClass('is-dragover');
})
.on('dragleave dragend drop', function() {
$(this).removeClass('is-dragover');
})
.on('drop', function(event) {
// Set file on drop
$('input[type=file]').prop('files', event.originalEvent.dataTransfer.files);
});
// Check if change event works
$('input[type=file]').on('change', function(event) {
$('#result span').text(event.target.files[0].name);
});
});Run Code Online (Sandbox Code Playgroud)
input {
display: block;
margin-bottom: 10px;
}
label {
padding: 20px;
display: inline-block;
border: 2px dashed grey;
}
label:hover {
background: lightgray;
cursor: pointer;
}
label.is-dragover {
background: grey;
}
#result {
margin-top: 10px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" id="file-field" name="file-field">
<label for="file-field">Click to select (works)<br>Drop file (doesn't work)</label>
<div id="result">
File on change event: <span></span>
</div>Run Code Online (Sandbox Code Playgroud)
您可以触发该change事件: $('input[type=file]').trigger('change');
$(document).ready(function() {
$('label').on('drag dragstart dragend dragover dragenter dragleave drop', function(event) {
event.preventDefault();
event.stopPropagation();
})
.on('dragover dragenter', function() {
$(this).addClass('is-dragover');
})
.on('dragleave dragend drop', function() {
$(this).removeClass('is-dragover');
})
.on('drop', function(event) {
// No idea if this is the right way to do things
$('input[type=file]').prop('files', event.originalEvent.dataTransfer.files);
$('input[type=file]').trigger('change');
});
$('input[type=file]').on('change', function(event) {
$('#result span').text(event.target.files[0].name);
});
});Run Code Online (Sandbox Code Playgroud)
input {
display: block;
margin-bottom: 10px;
}
label {
padding: 20px;
display: inline-block;
border: 2px dashed grey;
}
label:hover {
background: lightgray;
cursor: pointer;
}
label.is-dragover {
background: grey;
}
#result {
margin-top: 10px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" id="file-field" name="file-field">
<label for="file-field">Click to select (works)<br>Drop file (doesn't work)</label>
<div id="result">
File on change event: <span></span>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3267 次 |
| 最近记录: |