Web API —— Draggable(可拖拽的)
2024-08-19 星期一其实浏览器本身就有拖拽功能,只需要在元素上设置 draggable
属性即可。在拖动的时候会产生一个该元素的副本在鼠标上。
这是一个可拖拽的元素
html<div draggable="true"> 这是一个可拖拽的元素 </div>
# 拖拽事件
在拖拽元素时会触发以下的事件:
dragstart
- 开始拖拽dragend
- 拖拽结束drag
- 拖拽中
# 可放置区域事件
这些事件是当有可拖拽目标到可放置目标的时候触发的。
dragover
- 拖拽目标到可放置的目标dragenter
- 拖拽目标进入可放置的目标dragleave
- 拖拽目标离开可放置的目标drop
- 拖拽目标到可放置到目标中放下
这是一个可拖拽的元素
可放置区域
状态:未拖拽
# dataTransfer(拖拽数据)对象
这个对象用来传递拖拽数据,包括拖拽源和拖拽目标。
它有以下几个常用属性和方法:
dropEffect
- 放下效果effectAllowed
- 拖拽效果files
- 拖拽的文件列表items
- 拖拽的数据项列表types
- 拖拽的数据类型setDragImage
- 设置拖拽图片setData
- 设置拖拽数据getData
- 获取拖拽数据clearData
- 清空拖拽数据

可放置区域
html<div id="draggable" draggable="true">可拖拽的元素</div> <div id="droppable">可放置区域</div>
tsconst
const draggable: HTMLElement | null
draggable =var document: Document
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)document.Document.getElementById(elementId: string): HTMLElement | null
Returns a reference to the first object with the specified value of the ID attribute.@paramelementId String that specifies the ID value.getElementById('draggable') constconst droppable: HTMLElement | null
droppable =var document: Document
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)document.Document.getElementById(elementId: string): HTMLElement | null
Returns a reference to the first object with the specified value of the ID attribute.@paramelementId String that specifies the ID value.getElementById('droppable')const draggable: HTMLElement | null
draggable?.HTMLElement.addEventListener<K>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)addEventListener('dragstart', (event: DragEvent
event) => { // 设置拖拽数据event: DragEvent
event.DragEvent.dataTransfer: DataTransfer | null
Returns the DataTransfer object for the event. [MDN Reference](https://developer.mozilla.org/docs/Web/API/DragEvent/dataTransfer)dataTransfer!.DataTransfer.setData(format: string, data: string): void
Adds the specified data. [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/setData)setData('text/plain', 'hello') // 设置拖拽类型event: DragEvent
event.DragEvent.dataTransfer: DataTransfer | null
Returns the DataTransfer object for the event. [MDN Reference](https://developer.mozilla.org/docs/Web/API/DragEvent/dataTransfer)dataTransfer!.DataTransfer.dropEffect: "copy" | "none" | "link" | "move"
Returns the kind of operation that is currently selected. If the kind of operation isn't one of those that is allowed by the effectAllowed attribute, then the operation will fail. Can be set, to change the selected operation. The possible values are "none", "copy", "link", and "move". [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/dropEffect)dropEffect = 'copy' // 设置拖拽效果event: DragEvent
event.DragEvent.dataTransfer: DataTransfer | null
Returns the DataTransfer object for the event. [MDN Reference](https://developer.mozilla.org/docs/Web/API/DragEvent/dataTransfer)dataTransfer!.DataTransfer.effectAllowed: "copy" | "none" | "link" | "move" | "copyLink" | "copyMove" | "linkMove" | "all" | "uninitialized"
Returns the kinds of operations that are to be allowed. Can be set (during the dragstart event), to change the allowed operations. The possible values are "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", and "uninitialized", [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/effectAllowed)effectAllowed = 'copy' })const droppable: HTMLElement | null
droppable?.HTMLElement.addEventListener<K>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)addEventListener('dragover', (event: DragEvent
event) => {event: DragEvent
event.Event.preventDefault(): void
If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)preventDefault() })const droppable: HTMLElement | null
droppable?.HTMLElement.addEventListener<K>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)addEventListener('drop', (event: DragEvent
event) => {event: DragEvent
event.Event.preventDefault(): void
If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)preventDefault() constconst text: string
text =event: DragEvent
event.DragEvent.dataTransfer: DataTransfer | null
Returns the DataTransfer object for the event. [MDN Reference](https://developer.mozilla.org/docs/Web/API/DragEvent/dataTransfer)dataTransfer!.DataTransfer.getData(format: string): string
Returns the specified data. If there is no such data, returns the empty string. [MDN Reference](https://developer.mozilla.org/docs/Web/API/DataTransfer/getData)getData('text/plain')var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```@see[source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js)console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.@sincev0.1.100log(const text: string
text) })
~ cd ../