JavaScript practice tips: drag and drop events, drag and drop pictures into the page

HTML5 has added a drag event drag, which can be used to drag and drop external files into the page, and can realize file reading, uploading and other functions.

Drag , also known as drag, drag, drag in English .

The drag event is a new event operation in HTML5.

Drag and drop is when the user holds down the mouse button on an object, drags it to another location (another tab), and then releases the mouse button to drop the object there.

  • Object to be dragged : the content dragged by the mouse, which can be labels, pictures, text, etc.

  • Container : The new location where the dragged object is stored.

There are several kinds of objects to be dragged, including label nodes, pictures, links, selected text, and so on. In web pages, except for label nodes, which cannot be dragged and dropped by default , others ( pictures <img>, hyperlinks <a>, selected text ) can be dragged and dropped directly.

In order to make the label node draggable, draggablethe property set to true.

<div class="small" draggable="true">
   可拖动区域
</div>

After defining draggablethe properties, you can define the drag event for the label.

Note: The drag event is not compatible with the mousemove event, only one of them can be used.

1. Events related to the dragged object

Drag and drop is composed of two parts: drag and release, and the drag event is also divided into: related events of the dragged object and related events of the container .

  • Related events of the dragged object

event describe
drag start Fired when the user starts dragging an element. Usually in the listening function of this event, specify the dragged data .
drag Fired when the element is being dragged . During the dragging process, trigger continuously on the dragged node (every few hundred milliseconds)
carrying Fires when the user finishes dragging an element . Regardless of whether the drag is across windows or is canceled midway, dragendthe event will always be triggered.

The following example shows how to dynamically change the background color of the dragged node.

<div id="box" class="box" draggable="true">
</div>
<script>
    let box = document.getElementById("box");
    box.addEventListener("dragstart",function (e) {
        e.target.classList.add("dragging");
    });
    box.addEventListener("dragend",function (e) {
        e.target.classList.remove("dragging");
    });
</script>

 

When div#boxbeing dragged, it will turn into a yellow background. When the drag is over, it changes back to a red background.

2. Container related events

  • Container related events

event describe
carrier This event is fired when the object being dragged by the mouse enters the bounds of its container . Usually, in the listener function of this event, specify whether to allow the dragged data to be dropped on the current node . If the current node does not have a listener function for the event , or the listener function does not perform any operations, it means that data is not allowed to be dropped on the current node . Visually display the drag and drop into the current node, which is also set in the listener function of this event.
Dragover This event is fired when the object being dragged is dragged within the bounds of another object container . dragenterThe event is triggered when entering the node, and then as long as it does not leave the node, dragoverthe event will continue to be triggered .
dragleave This event is fired when the object being dragged by the mouse leaves its container bounds
drop Triggered on the container node when the dragged node or the selected text is released to the container node when the mouse is released. Note that if the current node does not allowdrop , or the user presses the ESC key to cancel the operation, this event will not be triggered . The listener function of this event is responsible for taking out the dragged data and performing relevant processing .

 Notice:

  • By default, browsers prevent anything from dropping onto HTML elements from happening.

  • To set the default event on the container (droppable area) event.preventDefault(), otherwise dropthe event will not be triggered.

  • The general blocking default event is written on dragoverthe dropevent.

The following example shows how to drag a node from the current parent node to another parent node.

<div class="dropzone">
    <div id="box" class="box" draggable="true">
        要拖动的div
    </div>
</div>

<div class="dropzone"></div>
<div class="dropzone"></div>
<div class="dropzone"></div>
<div class="dropzone"></div>
<div class="dropzone"></div>
<div class="dropzone"></div>
<script>
    let box = document.getElementById("box");
    let dropzone = document.querySelectorAll(".dropzone");
    box.addEventListener("dragstart",function (e) {
        let _box = this;
        // 开始拖拽的时候,让原来的 div 隐藏,要通过延迟代码执行。
        setTimeout(function () {
            _box.style.opacity = 0;
        },0);
    });
    box.addEventListener("dragend",function (e) {
        // 结束拖拽,原来的div恢复显示。
        e.target.style.opacity = 1;
    });

    dropzone.forEach(function (item,index) {
        item.addEventListener("dragenter",function (e) {
            e.target.classList.add("over");
        });
        item.addEventListener("dragover",function (e) {
            // 阻止默认事件
            e.preventDefault();
        }); 
        item.addEventListener("dragleave",function (e) {
            e.target.classList.remove("over");
        });
        item.addEventListener("drop",function (e) {
            e.preventDefault();  // 阻止默认事件
            // 把 div.box放入对应的div.dropzone 中
            e.target.appendChild(box);
        });
    });
</script>

3. Drag event execution sequence

  1. dragstart (the dragged element)

  2. dragenter (container)

  3. dragover (container)

  4. dragleave (container)

  5. drop (container)

  6. dragend (the dragged element)

From dragstartthe beginning to dragendthe end, the whole process is continuously triggering drag (the element being dragged). As shown in the figure below, only dragstart, drag, dragend events are reserved.

 

 4. Case: Drag and drop image files into the page

(1) preparation

Drag and drop the file into the page div.box tag. Customize the style.

 <div class="box" id="box">
        <span>把文件拖放在这里</span>
    </div>

 

must be dragoveradded disable default event code.

box.addEventListener("dragover",function (e) {
    e.preventDefault();
});

(2)DataTransfer.files

event.dataTransfer.filesThe property is a FileList object, which contains a set of local files, which can be used to transfer in the drag operation. If this drag and drop does not involve files, this property is an empty FileList object.

You can traverse the FileList, or use the index to obtain a file , and obtain the file 's name, type, size and other attributes.

let box = document.getElementById("box");
box.addEventListener("dragover",function (e) {
    e.preventDefault();
});
box.addEventListener("drop",function (e) {
    e.preventDefault();
    let file = e.dataTransfer.files[0];
    console.info( e.dataTransfer.files )
    console.info( file )
    console.info( file.name )
    console.info( file.type )
    console.info( file.size )
});

You can use the static method to get the path of the file. URL.createObjectURL(file)

(3) Drag and drop a single image into the page

box.addEventListener("drop",function (e) {
    e.preventDefault();
    box.innerHTML = "";
    // 获取文件
    let file = e.dataTransfer.files[0];
    // 获取文件 type
    console.info( file.type );
    // 判断文件是否是图片
    if( /image/.test(file.type)){
        console.info("图片");
    }else{
        box.innerHTML = "请拖入一个图片文件,如png,jpg或者gif";
        return false; // 终止函数运行
    }
    // 生成文件路径
    let url = URL.createObjectURL(file);
    // 创建一个 img 标签
    let img = document.createElement("img");
    img.src = url;
    // 把 img 添加到 box 里。
    box.appendChild(img) 
});

 

(4) Drag and drop multiple pictures into the page

box.addEventListener("drop",function (e) {
    e.preventDefault();
    box.innerHTML = "";
    // 获取文件列表
    let files = e.dataTransfer.files;
    [...files].forEach(function (item,index) {
        // 判断文件是否是图片
        if( /image/.test(item.type)){
            console.info("图片");
            // 生成文件路径
            let url = URL.createObjectURL(item);
            // 创建一个 img 标签
            let img = document.createElement("img");
            img.src = url;
            // 把 img 添加到 box 里。
            box.appendChild(img)
        }else{
            console.info(`文件${index}不是图片`);
        }
    });
});

 

Guess you like

Origin blog.csdn.net/weixin_42703239/article/details/128809385