목차
드래그 앤 드롭 이벤트
Syntax of Drag and Drop in HTML
Examples of Drag and Drop in HTML
Example #3
Conclusion
웹 프론트엔드 HTML 튜토리얼 HTML에서 드래그 앤 드롭

HTML에서 드래그 앤 드롭

Sep 04, 2024 pm 04:38 PM
html html5 HTML Tutorial HTML Properties HTML tags

다음 문서에서는 HTML의 드래그 앤 드롭에 대한 개요를 제공합니다. 드래그 앤 드롭은 편리한 기능 패턴으로 인해 웹 페이지에서 수동으로 입력을 제공하는 것으로 잘 알려진 최신 기능입니다. 드래그 앤 드롭 방식은 사용자가 소스 필드의 항목 목록에서 특정 데이터/옵션을 선택하고 이를 드래그하여 대상 필드에 드롭하는 과정으로 설명할 수 있습니다. 이는 HTML 웹 페이지의 여러 마우스 이벤트와 함께 문서 개체 모델을 사용하여 구현됩니다. 이 기능에 사용되는 다양한 이벤트로는 drag, dragstart, dragleave, dragenter, dragover, drop, dragend 및 dragexit가 있습니다.

드래그 앤 드롭 이벤트

최신 드래그 앤 드롭(dnd) 기능에는 여러 이벤트가 포함되어 있습니다. 다음과 같이 하나씩 살펴보겠습니다.

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.

Let’s see some data attributes on which Drag and drop operation going to happen:

  • dataTransfer.dropEffect [ = value ]: This attribute is used to show which operation is currently going on. One can set it to replace the already selected operation. The values included in it like a copy, link, none or move.
  • dataTransfer.effectAllowed [ = value ]: Whichever operations are allowed will be returned through this attribute. It’s also possible to set to changing an already selected operation.
  • dataTransfer.files: This data attribute is used to get fileList of the files which are going to be dragged.
  • dataTransfer.addElement(element): It’s used to insert the already existing element into a list of other elements that are useful to render the drag feedback.
  • dataTransfer.setDragImage(element, x, y): This attribute is a little bit the same as above for updating drag feedback and help to change already existed feedback
  • dataTransfer.clearData ( [ format ] ): It helps the user to remove data from the already defined format. If the user omitted the argument, the IT would remove all the data.
  • dataTransfer.setData(format, data): It’s one of the popular attributes used to add specified data.
  • data = dataTransfer.getData(format): This attribute in Drag and Drag operation is used to extract specified data. If there is no same data as it, it will return to the empty string.

Syntax of Drag and Drop in HTML

Here are a few steps defining the syntax for drag and drop:

Select the object to be a drag: Set attribute true to it.

<element draggable="true">
로그인 후 복사

Start dragging object:

function dragStart(ev){}
로그인 후 복사

Drop the object:

function dragDrop(ev){}
로그인 후 복사

Examples of Drag and Drop in HTML

The following example will show how exactly the drag and drop operation will perform in HTML.

Example #1

Code:

<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>
로그인 후 복사

Output:

Before drag and drop, option output will be as shown below:

HTML에서 드래그 앤 드롭

After performing the Drag and Drop operation, the output will be as follows:

HTML에서 드래그 앤 드롭

Example #2

Here we are going to see another example in which we will move the image from one location to another specified location as shown below code.

Code:

<!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>
로그인 후 복사

Output:

Before drag and drop operation, the output is:

HTML에서 드래그 앤 드롭

After the drag and drop operation is completed, it will look like this:

HTML에서 드래그 앤 드롭

Example #3

In this example, we are going to see how to drag and drop file at the specified location:

Code:

<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>
로그인 후 복사

Output:

HTML에서 드래그 앤 드롭

Conclusion

HTML drag and drop is one of the most important user interface entities that will use for different purposes like copying, deleting, or recording. It works on different events and attributes, as listed above. It performs the operation when you pick some object and then drop it at a specified location.

위 내용은 HTML에서 드래그 앤 드롭의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. 크로스 플레이가 있습니까?
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

HTML의 테이블 테두리 HTML의 테이블 테두리 Sep 04, 2024 pm 04:49 PM

HTML의 테이블 테두리 안내. 여기에서는 HTML의 테이블 테두리 예제를 사용하여 테이블 테두리를 정의하는 여러 가지 방법을 논의합니다.

HTML 여백-왼쪽 HTML 여백-왼쪽 Sep 04, 2024 pm 04:48 PM

HTML 여백-왼쪽 안내. 여기에서는 HTML margin-left에 대한 간략한 개요와 코드 구현과 함께 예제를 논의합니다.

HTML의 중첩 테이블 HTML의 중첩 테이블 Sep 04, 2024 pm 04:49 PM

HTML의 Nested Table에 대한 안내입니다. 여기에서는 각 예와 함께 테이블 내에 테이블을 만드는 방법을 설명합니다.

HTML 테이블 레이아웃 HTML 테이블 레이아웃 Sep 04, 2024 pm 04:54 PM

HTML 테이블 레이아웃 안내. 여기에서는 HTML 테이블 레이아웃의 값에 대해 예제 및 출력 n 세부 사항과 함께 논의합니다.

HTML 입력 자리 표시자 HTML 입력 자리 표시자 Sep 04, 2024 pm 04:54 PM

HTML 입력 자리 표시자 안내. 여기서는 코드 및 출력과 함께 HTML 입력 자리 표시자의 예를 논의합니다.

HTML 정렬 목록 HTML 정렬 목록 Sep 04, 2024 pm 04:43 PM

HTML 순서 목록에 대한 안내입니다. 여기서는 HTML Ordered 목록 및 유형에 대한 소개와 각각의 예에 대해서도 설명합니다.

HTML에서 텍스트 이동 HTML에서 텍스트 이동 Sep 04, 2024 pm 04:45 PM

HTML에서 텍스트 이동 안내. 여기서는 Marquee 태그가 구문과 함께 작동하는 방식과 구현할 예제에 대해 소개합니다.

HTML 온클릭 버튼 HTML 온클릭 버튼 Sep 04, 2024 pm 04:49 PM

HTML onclick 버튼에 대한 안내입니다. 여기에서는 각각의 소개, 작업, 예제 및 다양한 이벤트의 onclick 이벤트에 대해 설명합니다.

See all articles