Drag and Drop?in HTML
Sep 04, 2024 pm 04:38 PMThe following article provides an outline for Drag and Drop in HTML. Drag and Drop is the latest feature well-known for manually providing input in web pages due to its convenient functional pattern. The drag and drop method can be described as the process when a user selects a specific data/ option from the list of items in the source field, drag the same, and drop it in the destination field. It is implemented using Document Object Model, along with multiple mouse events from the HTML web page. The various events used in this feature are a drag, dragstart, dragleave, dragenter, dragover, drop, dragend and drag exit.
Events for Drag and Drop
There are multiple events included in the latest drag and drop (dnd) functionality; let’s see one by one as follows:
Sr. No | Events | Details Description |
1 | Drag | To drag entity(element or text) when the mouse is moved with the element to be dragged. |
2 | Dragstart | The very first step in drag and drop is dragstart. It gets executed when the user is going to start with dragging the object to the required location. |
3 | Dragenter | Dragenter event is used when the mouse is getting hover on the target element. |
4 | Dragleave | This event is used when the user releases a mouse from an element. |
5 | Dragover | This event occurs when a mouse is used to over an element. |
6 | Drop | This event is used at the end of the drag and drop process for drop element operation. |
7 | Dragend | This is one of the most important event in this process for releasing the mouse button from the element to complete the drag procedure. |
8 | Dragexit | This event status that the element is no longer in the drag process of urgent target selection of element. |
ドラッグ アンド ドロップ操作が行われるデータ屬性をいくつか見(jiàn)てみましょう:
- dataTransfer.dropEffect [ = value ]: この屬性は、現(xiàn)在実行中の操作を示すために使用されます。すでに選択されている操作を置き換えるように設(shè)定できます。コピー、リンク、なし、移動(dòng)など、それに含まれる値。
- dataTransfer.effectAllowed [ = value ]: 許可されている操作はすべて、この屬性を通じて返されます。すでに選択されている操作を変更する設(shè)定も可能です。
- dataTransfer.files: このデータ屬性は、ドラッグされるファイルの fileList を取得するために使用されます。
- dataTransfer.addElement(element): ドラッグ フィードバックのレンダリングに役立つ他の要素のリストに既存の要素を挿入するために使用されます。
- dataTransfer.setDragImage(element, x, y): この屬性は、ドラッグ フィードバックを更新するための上記の屬性と少し同じで、既存のフィードバックの変更に役立ちます
- dataTransfer.clearData ( [ format ] ): これは、ユーザーがすでに定義されている形式からデータを削除するのに役立ちます。ユーザーが引數(shù)を省略した場(chǎng)合、IT 部門(mén)はすべてのデータを削除します。
- dataTransfer.setData(format, data): これは、指定されたデータを追加するために使用される一般的な屬性の 1 つです。
- data = dataTransfer.getData(format): ドラッグ アンド ドラッグ操作のこの屬性は、指定されたデータを抽出するために使用されます。同じデータがない場(chǎng)合は空文字列に戻ります。
HTML でのドラッグ アンド ドロップの構(gòu)文
ドラッグ アンド ドロップの構(gòu)文を定義するいくつかの手順を次に示します。
ドラッグするオブジェクトを選択します: 屬性を true に設(shè)定します。
<element draggable="true">
オブジェクトのドラッグ開(kāi)始:
function dragStart(ev){}
オブジェクトをドロップします:
function dragDrop(ev){}
HTML でのドラッグ アンド ドロップの例
次の例は、ドラッグ アンド ドロップ操作が HTML でどのように正確に実行されるかを示します。
例 #1
コード:
<html> <head> <title>Drag and Drop Demo</title> <script> function allowDrop(ev) { ev.preventDefault(); } function dragStart(ev) { ev.dataTransfer.setData("text", ev.target.id); } function dragDrop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } </script> <style> #box { margin: auto; width: 30%; width: 21%; height:150px; border: 2px solid blue; padding: 2px; } #square1, #square2, #square3 { float: left; margin: 5px; padding: 10px; } #square1 { width: 30px; height: 30px; background-color: #BEA7CC; } #square2 { width: 60px; height: 60px; background-color: #B5D5F5; } #square3 { width: 90px; height: 90px; background-color:#F5B5C5 ; } h2 { font-size:20px; font-weight:bold; text-align:center; } </style> </head> <body> <h2>HTML DRAG AND DROP DEMO</h2> <div id = "box"> <div id="square1" draggable="true"ondragstart="dragStart(event)"></div> <div id="square2" draggable="true"ondragstart="dragStart(event)"></div> <div id="square3" ondrop="dragDrop(event)" ondragover="allowDrop(event)"></div> </div> </body> </html>
出力:
ドラッグ アンド ドロップする前、オプションの出力は次のようになります:
ドラッグ アンド ドロップ操作を?qū)g行すると、出力は次のようになります:
例 #2
ここでは、以下のコードに示すように、畫(huà)像をある場(chǎng)所から別の指定された場(chǎng)所に移動(dòng)する別の例を見(jiàn)ていきます。
コード:
<!DOCTYPE HTML> <html> <head> <script> function allowDrop(ev) { ev.preventDefault(); } function dragStart(ev) { ev.dataTransfer.setData("text", ev.target.id); } function dragDrop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } </script> <style> .divfirst { width: 250px; height: 150px; padding: 10px; border: 1px solid black; background-color: #F5F5F5; } p { font-size:20px; font-weight:bold; } </style> </head> <body> <p>Image Drag and Drop Demo</p> <div class="divfirst" ondrop="dragDrop(event)" ondragover="allowDrop(event)"> <img id="drag1" src="Jerry.jpeg" draggable="true" ondragstart="dragStart(event)" width="250" height="150"></div> <br> <div ??? class= "divfirst"ondrop="dragDrop(event)" ondragover="allowDrop(event)"></div> </body> </html>
出力:
ドラッグ アンド ドロップ操作前の出力は次のとおりです:
ドラッグ アンド ドロップ操作が完了すると、次のようになります。
例 #3
この例では、指定した場(chǎng)所にファイルをドラッグ アンド ドロップする方法を見(jiàn)ていきます。
コード:
<body> <div id="filedemo" style="min-height: 150px; border: 1px solid black;" ondragenter="document.getElementById('output').textContent = ''; event.stopPropagation(); event.preventDefault();" ondragover="event.stopPropagation(); event.preventDefault();" ondrop="event.stopPropagation(); event.preventDefault(); dodrop(event);"> DROP FILES HERE... </div> <script> function dodrop(event) { var dt = event.dataTransfer; var files = dt.files; for (var i = 0; i < files.length; i++) { output(" File " + i + ":\n(" + (typeof files[i]) + ") : <" + files[i] + " > " + files[i].name + " " ); } } function output(text) { document.getElementById("filedemo").textContent += text; } </script> </body>
出力:
結(jié)論
HTML ドラッグ アンド ドロップは、コピー、削除、記録などのさまざまな目的に使用される最も重要なユーザー インターフェイス エンティティの 1 つです。上記のように、さまざまなイベントや屬性に対して機(jī)能します。オブジェクトを選択し、指定された場(chǎng)所にドロップすると、操作が実行されます。
The above is the detailed content of Drag and Drop?in HTML. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The web page structure needs to be supported by core HTML elements. 1. The overall structure of the page is composed of , , which is the root element, which stores meta information and displays the content; 2. The content organization relies on title (-), paragraph () and block tags (such as ,) to improve organizational structure and SEO; 3. Navigation is implemented through and implemented, commonly used organizations are linked and supplemented with aria-current attribute to enhance accessibility; 4. Form interaction involves , , and , to ensure the complete user input and submission functions. Proper use of these elements can improve page clarity, maintenance and search engine optimization.

When using HTML5SSE, the methods to deal with reconnection and errors include: 1. Understand the default reconnection mechanism. EventSource retrys 3 seconds after the connection is interrupted by default. You can customize the interval through the retry field; 2. Listen to the error event to deal with connection failure or parsing errors, distinguish error types and execute corresponding logic, such as network problems relying on automatic reconnection, server errors manually delay reconnection, and authentication failure refresh token; 3. Actively control the reconnection logic, such as manually closing and rebuilding the connection, setting the maximum number of retry times, combining navigator.onLine to judge network status to optimize the retry strategy. These measures can improve application stability and user experience.

Doctype is a statement that tells the browser which HTML standard to use to parse the page. Modern web pages only need to be written at the beginning of the HTML file. Its function is to ensure that the browser renders the page in standard mode rather than weird mode, and must be located on the first line, with no spaces or comments in front of it; there is only one correct way to write it, and it is not recommended to use old versions or other variants; other such as charset, viewport, etc. should be placed in part.

Client-sideformvalidationcanbedonewithoutJavaScriptbyusingHTMLattributes.1)Userequiredtoenforcemandatoryfields.2)ValidateemailsandURLswithtypeattributeslikeemailorurl,orusepatternwithregexforcustomformats.3)Limitvaluesusingmin,max,minlength,andmaxlen

Use tags in HTML to group options in the drop-down menu. The specific method is to wrap a group of elements and define the group name through the label attribute, such as: 1. Contains options such as apples, bananas, oranges, etc.; 2. Contains options such as carrots, broccoli, etc.; 3. Each is an independent group, and the options within the group are automatically indented. Notes include: ① No nesting is supported; ② The entire group can be disabled through the disabled attribute; ③ The style is restricted and needs to be beautified in combination with CSS or third-party libraries; plug-ins such as Select2 can be used to enhance functions.

HTML5, CSS and JavaScript should be efficiently combined with semantic tags, reasonable loading order and decoupling design. 1. Use HTML5 semantic tags, such as improving structural clarity and maintainability, which is conducive to SEO and barrier-free access; 2. CSS should be placed in, use external files and split by module to avoid inline styles and delayed loading problems; 3. JavaScript is recommended to be introduced in front, and use defer or async to load asynchronously to avoid blocking rendering; 4. Reduce strong dependence between the three, drive behavior through data-* attributes and class name control status, and improve collaboration efficiency through unified naming specifications. These methods can effectively optimize page performance and collaborate with teams.

To use HTML button elements to achieve clickable buttons, you must first master its basic usage and common precautions. 1. Create buttons with tags and define behaviors through type attributes (such as button, submit, reset), which is submitted by default; 2. Add interactive functions through JavaScript, which can be written inline or bind event listeners through ID to improve maintenance; 3. Use CSS to customize styles, including background color, border, rounded corners and hover/active status effects to enhance user experience; 4. Pay attention to common problems: make sure that the disabled attribute is not enabled, JS events are correctly bound, layout occlusion, and use the help of developer tools to troubleshoot exceptions. Master this

It is more convenient to submit form data using HTML5's FormData API. 1. It can automatically collect form fields with name attribute or manually add data; 2. It supports submission in multipart/form-data format through fetch or XMLHttpRequest, which is suitable for file upload; 3. When processing files, you only need to append the file to FormData and send a request; 4. Note that the same name field will be overwritten, and JSON conversion and no nesting structure need to be handled.
