参考答案:
HTML5 的拖拽(Drag and Drop)API 允许用户通过拖拽操作在网页上移动元素或数据。这个 API 是在 HTML5 中引入的,它提供了一种标准的方式来实现拖拽功能。以下是对 HTML5 拖拽 API 的详细介绍:
draggable
属性为 true
,元素可以成为拖拽源。使元素可拖拽:
draggable="true"
属性。处理拖拽事件:
dragstart
:当拖拽操作开始时触发。通常用于设置拖拽数据。drag
:在拖拽过程中不断触发。用于提供实时反馈。dragend
:拖拽操作结束时触发。用于清理或更新 UI。处理拖拽目标:
dragenter
:当拖拽元素进入目标区域时触发。dragover
:当拖拽元素悬停在目标区域上方时触发。必须调用 event.preventDefault()
才能接受拖拽。dragleave
:当拖拽元素离开目标区域时触发。drop
:当拖拽元素在目标区域放下时触发。用于处理放置逻辑。HTML:
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>HTML5 Drag and Drop</title> 7 <style> 8 #drag-source { 9 width: 100px; 10 height: 100px; 11 background-color: lightblue; 12 margin: 20px; 13 text-align: center; 14 line-height: 100px; 15 cursor: move; 16 } 17 #drop-target { 18 width: 200px; 19 height: 200px; 20 background-color: lightgreen; 21 border: 2px dashed gray; 22 margin: 20px; 23 text-align: center; 24 line-height: 200px; 25 } 26 </style> 27</head> 28<body> 29 <div id="drag-source" draggable="true">Drag me</div> 30 <div id="drop-target">Drop here</div> 31 32 <script> 33 const dragSource = document.getElementById('drag-source'); 34 const dropTarget = document.getElementById('drop-target'); 35 36 // Drag start event 37 dragSource.addEventListener('dragstart', (event) => { 38 event.dataTransfer.setData('text/plain', 'Dragged data'); 39 }); 40 41 // Drag over event 42 dropTarget.addEventListener('dragover', (event) => { 43 event.preventDefault(); // Necessary to allow dropping 44 dropTarget.style.backgroundColor = 'lightyellow'; 45 }); 46 47 // Drag leave event 48 dropTarget.addEventListener('dragleave', () => { 49 dropTarget.style.backgroundColor = 'lightgreen'; 50 }); 51 52 // Drop event 53 dropTarget.addEventListener('drop', (event) => { 54 event.preventDefault(); 55 dropTarget.style.backgroundColor = 'lightgreen'; 56 const data = event.dataTransfer.getData('text/plain'); 57 dropTarget.textContent = `Dropped: ${data}`; 58 }); 59 </script> 60</body> 61</html>
draggable
属性:使元素可以被拖拽。设置 draggable="true"
启用拖拽。dataTransfer
对象:在 dragstart
事件中使用 event.dataTransfer
设置和获取拖拽数据。preventDefault()
:在 dragover
事件中调用 event.preventDefault()
允许放置操作。最近更新时间:2024-08-22