찾다
웹 프론트엔드HTML 튜토리얼HTML에서 드래그 앤 드롭

HTML에서 드래그 앤 드롭

Sep 04, 2024 pm 04:38 PM
htmlhtml5HTML TutorialHTML PropertiesHTML 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"></element>

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:


<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>


<h2 id="HTML-DRAG-AND-DROP-DEMO">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>

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:



<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>


<p>Image Drag and Drop Demo</p>
<div class="divfirst" ondrop="dragDrop(event)" ondragover="allowDrop(event)">
<img  src="/static/imghwm/default1.png" data-src="Jerry.jpeg" class="lazy" id="drag1" draggable="true" ondragstart="dragStart(event)"    style="max-width:90%"  style="max-width:90%" alt="HTML에서 드래그 앤 드롭" >
</div>
<br>
<div class="divfirst" ondrop="dragDrop(event)" ondragover="allowDrop(event)"></div>

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:

<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>

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으로 문의하세요.
HTML vs. CSS 및 JavaScript : 웹 기술 비교HTML vs. CSS 및 JavaScript : 웹 기술 비교Apr 23, 2025 am 12:05 AM

HTML, CSS 및 JavaScript는 최신 웹 페이지를 구축하기위한 핵심 기술입니다. 1. HTML 웹 페이지 구조를 정의합니다. 2. CSS는 웹 페이지의 모양을 담당합니다.

마크 업 언어로서의 HTML : 기능과 목적마크 업 언어로서의 HTML : 기능과 목적Apr 22, 2025 am 12:02 AM

HTML의 기능은 웹 페이지의 구조와 내용을 정의하는 것이며, 그 목적은 정보를 표시하는 표준화 된 방법을 제공하는 것입니다. 1) HTML은 타이틀 및 단락과 같은 태그 및 속성을 통해 웹 페이지의 다양한 부분을 구성합니다. 2) 콘텐츠 및 성능 분리를 지원하고 유지 보수 효율성을 향상시킵니다. 3) HTML은 확장 가능하므로 사용자 정의 태그가 SEO를 향상시킬 수 있습니다.

HTML, CSS 및 JavaScript의 미래 : 웹 개발 동향HTML, CSS 및 JavaScript의 미래 : 웹 개발 동향Apr 19, 2025 am 12:02 AM

HTML의 미래 트렌드는 의미론 및 웹 구성 요소이며 CSS의 미래 트렌드는 CSS-In-JS 및 CSShoudini이며, JavaScript의 미래 트렌드는 WebAssembly 및 서버리스입니다. 1. HTML 시맨틱은 접근성과 SEO 효과를 향상시키고 웹 구성 요소는 개발 효율성을 향상 시키지만 브라우저 호환성에주의를 기울여야합니다. 2. CSS-in-JS는 스타일 관리 유연성을 향상 시키지만 파일 크기를 증가시킬 수 있습니다. CSShoudini는 CSS 렌더링의 직접 작동을 허용합니다. 3. Webosembly는 브라우저 애플리케이션 성능을 최적화하지만 가파른 학습 곡선을 가지고 있으며 서버리스는 개발을 단순화하지만 콜드 스타트 ​​문제의 최적화가 필요합니다.

HTML : 구조, CSS : 스타일, 자바 스크립트 : 동작HTML : 구조, CSS : 스타일, 자바 스크립트 : 동작Apr 18, 2025 am 12:09 AM

웹 개발에서 HTML, CSS 및 JavaScript의 역할은 다음과 같습니다. 1. HTML은 웹 페이지 구조를 정의하고, 2. CSS는 웹 페이지 스타일을 제어하고 3. JavaScript는 동적 동작을 추가합니다. 그들은 함께 현대 웹 사이트의 프레임 워크, 미학 및 상호 작용을 구축합니다.

HTML의 미래 : 웹 디자인의 진화 및 트렌드HTML의 미래 : 웹 디자인의 진화 및 트렌드Apr 17, 2025 am 12:12 AM

HTML의 미래는 무한한 가능성으로 가득합니다. 1) 새로운 기능과 표준에는 더 많은 의미 론적 태그와 WebComponents의 인기가 포함됩니다. 2) 웹 디자인 트렌드는 반응적이고 접근 가능한 디자인을 향해 계속 발전 할 것입니다. 3) 성능 최적화는 반응 형 이미지 로딩 및 게으른로드 기술을 통해 사용자 경험을 향상시킬 것입니다.

HTML vs. CSS vs. JavaScript : 비교 개요HTML vs. CSS vs. JavaScript : 비교 개요Apr 16, 2025 am 12:04 AM

웹 개발에서 HTML, CSS 및 JavaScript의 역할은 다음과 같습니다. HTML은 컨텐츠 구조를 담당하고 CSS는 스타일을 담당하며 JavaScript는 동적 동작을 담당합니다. 1. HTML은 태그를 통해 웹 페이지 구조와 컨텐츠를 정의하여 의미를 보장합니다. 2. CSS는 선택기와 속성을 통해 웹 페이지 스타일을 제어하여 아름답고 읽기 쉽게 만듭니다. 3. JavaScript는 스크립트를 통해 웹 페이지 동작을 제어하여 동적 및 대화식 기능을 달성합니다.

HTML : 프로그래밍 언어입니까 아니면 다른 것입니까?HTML : 프로그래밍 언어입니까 아니면 다른 것입니까?Apr 15, 2025 am 12:13 AM

Htmlisnotaprogramminglanguage; itisamarkuplanguage.1) htmlstructuresandformatswebcontentusingtags.2) itworksporstylingandjavaScriptOfforIncincivity, WebDevelopment 향상.

HTML : 웹 페이지 구조 구축HTML : 웹 페이지 구조 구축Apr 14, 2025 am 12:14 AM

HTML은 웹 페이지 구조를 구축하는 초석입니다. 1. HTML은 컨텐츠 구조와 의미론 및 사용 등을 정의합니다. 태그. 2. SEO 효과를 향상시키기 위해 시맨틱 마커 등을 제공합니다. 3. 태그를 통한 사용자 상호 작용을 실현하려면 형식 검증에주의를 기울이십시오. 4. 자바 스크립트와 결합하여 동적 효과를 달성하기 위해 고급 요소를 사용하십시오. 5. 일반적인 오류에는 탈수 된 레이블과 인용되지 않은 속성 값이 포함되며 검증 도구가 필요합니다. 6. 최적화 전략에는 HTTP 요청 감소, HTML 압축, 시맨틱 태그 사용 등이 포함됩니다.

See all articles

핫 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 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전