首页  >  文章  >  web前端  >  拖放 HTML 元素和文件

拖放 HTML 元素和文件

王林
王林原创
2024-09-12 10:31:20501浏览

网络应用程序对于数据收集/摄取很有用。如果收集和存储数据的机制易于使用,则可以积累大量有用的数据进行数据处理。将数据从一个位置移动到另一个位置的一种简单方法是 Web 应用程序上的拖放功能。

在这篇文章中,我展示了三个示例,说明如何使用 JavaScript 拖放编程来移动和存储 HTML 元素数据和文件。

示例 0:拖放 HTML 元素

<!DOCTYPE html>
<html>
<head></head>
<body>

<h1>Example 0: Drag and Drop HTML text/elements</h1>
<div id="HTML_text" draggable="true" class="dragElement">HTML text</div>

<br><br>

<div id="dropArea" class="dropArea"> Drop for Example 0 & 1</div>

<style>
.dropArea { height: 200px;
    width: 200px;
    border-radius: 15px;
    border: 0.25px solid black;
    background-color: #7084c4;
}

.HTML_text { cursor: move; }
</style>
<script>
var example;
var other_data_related_to_dragEvent = {};
var html_element_drag_list_metaData = [];


// ----------------------------------------------------
// Drag functionality: Example 0
// ----------------------------------------------------
document.getElementById("HTML_text").addEventListener("dragstart", processEvent_drag_example0, false);
// document.getElementById("HTML_text").addEventListener("dragend", processEvent_drag_example0, false); // to stop

function processEvent_drag_example0(event) {
    example = 0;
    event.dataTransfer.setData('text/plain', event.target.id);
}
// ----------------------------------------------------

// ----------------------------------------------------
// Drop functionality: Example 0 and 1
// ----------------------------------------------------
document.getElementById("dropArea").addEventListener("drop", processEvent_drop, false);
document.getElementById("dropArea").addEventListener("dragover", processEvent_dragover, false);

function processEvent_drop(event) {

    // Stop defaults and allow drop events
    event.preventDefault();

    // Detects files dragged from pc 
    html_element_drag_list_metaData.push(event.dataTransfer.files);
    console.log('html_element_drag_list_metaData: ', html_element_drag_list_metaData);

    // Detects html elements dragged from the html page
    const data = event.dataTransfer.getData('text/plain');
    console.log('data: ', data);
    if (data.length != 0) {
      // find the draggable element based on the data
      const dragElement = document.getElementById(data);
      console.log('dragElement: ', dragElement);

      // Append the draggable element 
      event.target.appendChild(dragElement);

    }
}

function processEvent_dragover(event) {
  // Stop defaults and allow drop events
  event.preventDefault();
}
// -------------------------------------------------

</script>
</body>
</html>

将HTML文本(HTML text)拖放到紫色dropArea之前

Drag and Drop HTML elements and files

将HTML文本(HTML text)拖放到紫色dropArea后

Drag and Drop HTML elements and files

在示例 0 中,HTML 文本元素实际上已移至放置区域。 HTML 文本的 div 的 id 出现在变量数据中,因此可以跟踪 dropArea 内的元素 id。此示例对于组织/存储在 Web 应用程序上编写的现有 html 非常有用,但在大多数数据摄取情况下,人们希望组织/存储来自不同位置的数据。

示例 1:文件上传表示为可拖动的 HTML 元素/表情符号

此示例是拖动 HTML 元素和拖动文件之间的交叉示例。可以使用“浏览”按钮选择一个文件;将文件拖到浏览按钮或单击浏览按钮选择文件。选择文件后会出现一个表情符号,表情符号的出现以 HTML 元素的形式表示该文件。然后可以将代表文件的 HTML 元素 emoji 拖到 dropArea 进行数据摄取/存储。

<!DOCTYPE html>
<html>
<head></head>
<body>

<h1>Example 1: Click button create drag and drop elements</h1>
<input type="file" id="upload_file" accept="audio/*" style="display:block" multiple>
<div id="file_name" style="display:none"></div>
<div id="base64_string" style="display:none"></div>
<div id="base64_string_icon" draggable="true" class="dragElement" style="display:none">?</div>

<br><br>

<div id="dropArea" class="dropArea"> Drop for Example 0 & 1</div>

<style>
.dropArea { height: 200px;
    width: 200px;
    border-radius: 15px;
    border: 0.25px solid black;
    background-color: #7084c4;
}

.HTML_text { cursor: move; }
</style>

<script>
var example;
var other_data_related_to_dragEvent = {};
var html_element_drag_list_metaData = [];

// ----------------------------------------------------
// Drag functionality: Example 1
// ----------------------------------------------------
// The eventlistener needs to be always running, to detect which file the user selected with browse
document.getElementById("upload_file").addEventListener("change", previewInput_drop, false);

async function previewInput_drop(event) {

    // Take the first file
    const file = event.target.files[0];  // first file in the list of selected files, better for selecting multiple files at one time
    // console.log("file :", file);

    document.getElementById("file_name").innerHTML = file.name;

    // ---------------------

    const reader = new FileReader();

    reader.onload = async function(e){
        document.getElementById("base64_string").innerHTML = e.target.result;
        document.getElementById("base64_string_icon").style.display = "block";
    }

    reader.readAsDataURL(file);
}


document.getElementById("base64_string_icon").addEventListener("dragstart", processEvent_drag_example1, false);

function processEvent_drag_example1(event) {
    example = 1;
    event.dataTransfer.setData('text/plain', event.target.id);
}

// ----------------------------------------------------

// ----------------------------------------------------
// Drop functionality: Example 0 and 1
// ----------------------------------------------------
document.getElementById("dropArea").addEventListener("drop", processEvent_drop, false);
document.getElementById("dropArea").addEventListener("dragover", processEvent_dragover, false);

function processEvent_drop(event) {

    // Stop defaults and allow drop events
    event.preventDefault();

    // Detects files dragged from pc 
    html_element_drag_list_metaData.push(event.dataTransfer.files);
    console.log('html_element_drag_list_metaData: ', html_element_drag_list_metaData);

    // Detects html elements dragged from the html page
    const data = event.dataTransfer.getData('text/plain');
    console.log('data: ', data);
    if (data.length != 0) {
      // find the draggable element based on the data
      const dragElement = document.getElementById(data);
      console.log('dragElement: ', dragElement);

      // Append the draggable element 
      event.target.appendChild(dragElement);

    }
}

function processEvent_dragover(event) {
  // Stop defaults and allow drop events
  event.preventDefault();
}
// -------------------------------------------------

</script>
</body>
</html>

选择文件之前

Drag and Drop HTML elements and files

将文件拖至浏览按钮

Drag and Drop HTML elements and files

将代表文件表情符号拖至 dropArea

Drag and Drop HTML elements and files

示例 2:拖放 HTML 元素

在此示例中,可以一次高效地将多个文件拖动到 dropArea。

<!DOCTYPE html>
<html>
<head></head>
<body>

<h1>Example 2: Drag and drop files</h1>
<input type="file" id="upload_file_dragdrop" style="display:block" class="dropArea1" multiple>

<br><br>

<button id="use_moved_data" onclick="use_moved_data()">use_moved_data</button>

<!-- ---------------------------------------- -->
<!-- CSS -->
<style>
.dropArea1 { height: 200px;
    width: 200px;
    border-radius: 15px;
    border: 0.25px solid black;
    background-color: #56b06e;
}
</style>
<!-- ---------------------------------------- -->

<script>
var other_data_related_to_dragEvent = {};
var html_element_drag_list_metaData = [];

// ----------------------------------------------------
// Drag and Drop functionality: Example 2
// ----------------------------------------------------
document.getElementById("upload_file_dragdrop").addEventListener("change", previewInput, false);

async function previewInput(event) {

    // For multiple files
    const allFiles = event.target.files;
    // console.log("allFiles :", allFiles);

    var i = 0;
    while (i < allFiles.length) {

        const file = allFiles[i];
        // console.log("file :", file);

        await obtain_fileInfo(file)
            .then(base64str => { other_data_related_to_dragEvent[file.name] = base64str; })
            .catch(error => console.error(error));

        i = i + 1;
    }

    // ---------------------
}

async function obtain_fileInfo(file) {
    var base64_string = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = async function(e){ 
            resolve(e.target.result); // inside resolve is the value that the function returns
        };
        reader.readAsDataURL(file);
    });
     return base64_string;
}

// ----------------------------------------------------

async function use_moved_data() {
    console.log('html_element_drag_list_metaData: ', html_element_drag_list_metaData);
    console.log('other_data_related_to_dragEvent: ', other_data_related_to_dragEvent);
}

</script>
</body>
</html>

将文件拖入 dropArea 之前

Drag and Drop HTML elements and files

将文件拖入 dropArea 并按下 use_moved_data 按钮后

Drag and Drop HTML elements and files

我们可以看到拖入dropArea的三个文件的base64字符串数据!然后可以将 Base64 字符串数据保存为 Blob 对象并通过 Internet 传输。

我希望这些拖放 HTML 元素和文件的方法对某人有所帮助。

祝你练习愉快! ?

? GitHub | ?练习 Datscy @ Dev.to | ?练习 Datscy @ Medium

参考

  1. 如何在 JavaScript 中创建拖放功能:分步教程:https://medium.com/@future_fanatic/how-to-create-drag-and-drop-functionality-in-javascript-分步教程-8ea236ef9416
  2. 用 JavaScript 读取文件:https://web.dev/articles/read-files

以上是拖放 HTML 元素和文件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn