<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag & Drop 示例</title>
<style>
#drop_area {
width: 300px;
height: 200px;
border: 2px dashed #aaa;
text-align: center;
line-height: 200px;
font-size: 24px;
}
#preview {
width: 100px;
height: 100px;
border: 1px solid #000;
display: none;
position: absolute;
top: 30px;
left: 30px;
}
img {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<div id="drop_area">将图片拖拽到这里</div>
<div id="preview"><img src="" alt="预览图片" id="preview_img"></div>
<script>
let dropArea = document.getElementById('drop_area');
let preview = document.getElementById('preview');
let previewImg = document.getElementById('preview_img');
// 拖拽图片进入区域时
dropArea.addEventListener('dragenter', function(event) {
event.stopPropagation();
event.preventDefault();
});
// 拖拽图片在区域中时
dropArea.addEventListener('dragover', function(event) {
event.stopPropagation();
event.preventDefault();
preview.style.display = 'block';
});
// 拖拽图片离开区域时
dropArea.addEventListener('dragleave', function(event) {
event.stopPropagation();
event.preventDefault();
preview.style.display = 'none';
});
// 拖拽图片放下时
dropArea.addEventListener('drop', function(event) {
event.stopPropagation();
event.preventDefault();
let files = event.dataTransfer.files;
if (files.length > 0) {
// 使用FileReader读取图片
let fileReader = new FileReader();
fileReader.o
评论已关闭