<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽和单击上传文件</title>
<style>
#drop_area {
width: 300px;
height: 200px;
border: 2px dashed #aaa;
text-align: center;
padding: 50px;
cursor: pointer;
position: relative;
overflow: hidden;
}
#fake_input {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
}
</style>
</head>
<body>
<div id="drop_area">
<form id="form" action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="dir" value="image">
<input type="file" id="fake_input" name="file1" multiple>
</form>
将文件拖拽到此处上传<br>
或<br>
点击这里选择文件
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function () {
var $dropArea = $('#drop_area');
$dropArea.on('dragenter dragover', function (e) {
e.stopPropagation();
e.preventDefault();
$(this).css('border-color', 'green');
});
$dropArea.on('dragleave', function (e) {
e.stopPropagation();
e.preventDefault();
$(this).css('border-color', '#aaa');
});
$dropArea.on('drop', function (e) {
e.stopPropagation();
e.preventDefault();
$(this).css('border-color', '#aaa');
var files = e.originalEvent.dataTransfer.files;
if (files.length) {
$('#form').submit();
}
});
$('#fake_input').on('change', function () {
$('#form').submit();
});
});
</script>
</body>
</html>
这段代码使用jQuery为一个div
元素添加了拖拽上传文件的功能。当用户拖拽文件到div
上时,会有视觉反馈,并在释放鼠标按钮时触发表单提交。同时,也可以通过点击div
并选择文件来上传。这个例子简单明了,并且易于理解和应用。