H5 drag and drop and file upload

1. Set drag

The picture element comes with drag and drop attributes, and other elements can set draggable attributes.

<div draggable="true"></div>

After the element is set to drag, you can see the drag. 

When dragging is not set, other elements except the picture element are not draggable.

 

1.1 Drag and drop event

  1.  ondragstar: Departure before dragging, the event will only trigger once.
  2. ondrag: Before the drag, the trigger is triggered between the end of the drag, the event will be continuously triggered,
  3. ondragend: Triggered by the end of the drag, the event is only triggered once.
        let box = document.querySelector('.box')
        box.ondragstart = function (e) {
           console.log('拖拽开始')
        }
        box.ondrag = function (e) {
           console.log('拖拽ing.......')
        }
        box.ondragend = function (e) {
           console.log('拖拽结束')
        }

 Printed results:

 1.2 Drag event of target element

  1. ondragenter: Enter the target element to trigger
  2. ondragover: trigger when entering the target element
  3. ondragleave: trigger when leaving the target element
  4. ondrop: release the mouse on the target element
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .wrap {
            float: left;
            width: 300px;
            height: 400px;
            background-color: skyblue;
            font-size:20px;
            color:purple;
            text-align: center;
            line-height:400px;
        }

        .box {
            float: right;
            width: 150px;
            height: 150px;
            background-color: #ccc;
        }
    </style>
</head>

<body>
    <div class="box" draggable="true"></div>
    <!-- <img src="https://img9.doubanio.com/view/photo/l/public/p2492913246.webp" width="200"> -->
    <div class="wrap">把元素移入这里</div>
    <script>
        let wrap = document.querySelector('.wrap')
        let box = document.querySelector(".box");
        //被拖拽元素对象事件
         // dragstart 拖拽开始时触发,只触发一次
         box.ondragstart = function () {
            this.style.background = 'blue';

        }

        // drag拖拽触发的事件,连续触发,只要鼠标不松开会一直触发
        box.ondrag = function () {
            this.style.background = 'yellow';
        }

        // dragend 拖拽结束时,触发的事件,只要鼠标一松开就触发
        box.ondragend = function () {
            this.style.background = 'pink';
        }


        //拖拽元素被拖拽到的对象事件
        //进入目标元素触发
        wrap.ondragenter = function () {
            this.innerHTML = '元素进入了'
        }
        //离开目标元素触发
        wrap.ondragleave = function () {
            this.innerHTML = '讨厌,谁让你离开的'
        }
        //在目标元素中移动触发
        wrap.ondragover = function () {
            this.innerHTML = '元素移动了'
            return false;
        }
        //在目标元素上释放鼠标触发
        wrap.ondrop = function () {
            this.innerHTML = '鼠标松开了'
        }
    </script>
</body>

</html>

 

1.2 dataTransfer object

dataTransfer is a property of the drag event object.

1.setData (): Set the data key and value (must be a string)

2.getData (): Get data, according to the key value, get the corresponding value

        let box = document.querySelector(".box");
        let wrap = document.querySelector(".wrap");
        //datatransfer 拖拽对象的事件属性
        box.ondragstart = function (e) {
            this.style.background = 'pink';
            e.dataTransfer.setData('key', this.className);
            // 火狐必须加上这一行代码才能触发drag和dragend事件
        }
        wrap.ondragover = function () {
            console.log(1)
            return false
        }
        // 设置的key在这里可以使用
        wrap.ondrop = function (e) {
            this.style.background = 'skyblue';
            //获取box元素
            let key =document.querySelector("."+ e.dataTransfer.getData("key"));
            // console.log(key);
            //删除box
            document.body.removeChild(key);
        }

 Elements are deleted after being moved in

3.effectAllowed: Set the cursor style (none, copy, copyLink, copyMove, link, linkMove, move, all and uninitialized)

box.ondragstart = function (e) {
    e.dataTransfer.effectAllowed = 'link';
}

4.files: Get externally dragged files and return a filesList list. There is a type attribute under filesList to return the file type

wrap.ondrop = function (e) {
    let a = e.dataTransfer;
    console.log(a.files)
    return false;
}

After I dragged the file in, the printed result is as follows (you can see the size, type, and last modification time of the picture)

 2. Read file information

You can read the file information stored locally through the FileReader object, and use the File object to specify the file data to be read.

2.1 FileReader reads file information (use drag and drop to read file information)

  1. The readAsDataURL parameter is the file object to be read

  2. onload triggers this event when the file reading is completed successfully

  3. this. result Get the file data read

The sample code is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            width: 800px;
            height: 100px;
            margin: 20px auto;
            border-radius: 5px;
            background-color: #ccc;
            font-size: 18px;
            font-weight: bold;
            color: #fff;
            text-align: center;
            line-height: 100px;
        }

        .container {
            width: 800px;
            height: 400px;
            margin: 20px auto;
            border: 2px solid skyblue;
        }

        .container>img {
            width: 200px;
        }
    </style>
</head>

<body>
    <div class="box">把图片拖至这里</div>
    <!-- 用来展示已经拖入的图片 -->
    <div class="container"></div>

    <script>
        //获取元素
        let box = document.querySelector('.box');
        let container = document.querySelector(".container");

        box.ondragover = function (ev) {
            //阻止默认事件
            ev.preventDefault();
            //阻止事件冒泡
            ev.stopPropagation();
            return false;
        }

        box.ondrop = function (ev) {
            ev.preventDefault()
            ev.stopPropagation()
            //获取文件信息
            console.log(ev.dataTransfer.files)
            let file = ev.dataTransfer.files[0];

            //创建读取文件的对象
            let oFiles = new FileReader();
            console.log(oFiles)
            //获取文件的URL地址
            oFiles.readAsDataURL(file);
            //文件信息读取完成之后会触发onload 事件
            oFiles.onload = function () {
                let src = this.result;
                // console.log(src);
                if (file.type.includes('image')) {
                    //创建图片标签
                    let img = new Image();
                    //设置渲染图片的URL地址
                    img.src = src;
                    //将图片作为contianer的子元素渲染到页面中
                    container.appendChild(img);
                }
            }
            return false;
        }
    </script>
</body>

</html>

2.2 Use form fields to read file information

The DOM element returned by the form field has a files attribute. The value of this attribute is a Files object, which stores the information of the selected file.

After selecting the file, start the onchange event.

A piece of code:

         //表单域返回的DOM元素身上有一个files的属性,这个属性值就是一个Files对象, 里面保存选中的文件的信息 
        var file = document.querySelector('#file');
        file.onchange = function() {
            console.dir(this);
        }

Use the form to read the file information:

<input type="file" name="file" multiple />

<script>
    var file = document.querySelector("input")

    file.addEventListener("change",function(){
        console.log(this.files)
    },false)

</script>

Case

html code:

   <input type="file" id='file' multiple/>
    <div class="container"></div>

JavaScript code

       //获取元素
        let container = document.querySelector(".container");
        let file = document.querySelector('#file');
        file.onchange = function () {
            let files = this.files;
            let length = files.length;
            if(length){
                for(let i = 0; i < length; i++){
                    Render(files[i])
                }
            }
        }
        function Render(file) {
            //创建读取文件的对象
            let oFile = new FileReader();

            // 通过读取文件对象的readAsDataURL 方法读取指定的文件
            oFile.readAsDataURL(file);

            //文件信息读取完毕触发onload事件
            oFile.onload = function() {
                let src = this.result;
                //创建图片标签
                let img = new Image();
                img.src = src;
                container.appendChild(img);
            }
        }

The final effect is that you can upload multiple pictures at the same time

 

Published 34 original articles · received 145 · views 7191

Guess you like

Origin blog.csdn.net/lhrdlp/article/details/105200995