html5 drag 文件拖拽浅淡

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .container {
            width: 200px;
            height: 200px;
            background: #ccc;
            margin: 60px auto;
            border: 1px solid silver;
            text-align: center;
            line-height: 200px;
        }
    </style>
    <script>
        window.onload = function () {
            //ondragenter  拖拽文件进入时触发的事件
            //ondragleave  拖拽文件离开时触发的事件
            //ondragover   拖拽鼠标悬停的时候触发的事件
            //ondrop       释放鼠标的时候触发的事件,(前提是ondragover阻止默认事件才能被被触发,本身也要阻止默认事件)
            //为了更好的兼容,建议都使用addEventListener来进行绑定
            let odiv = document.getElementById('container');

            odiv.addEventListener('dragenter', function () {
                this.innerHTML = '请释放鼠标'
            }, false);

            odiv.addEventListener('dragleave', function () {
                this.innerHTML = '请将文件拖拽到此处';
            });
            odiv.addEventListener('dragover', function (ev) {
                console.log('鼠标正在上面');
                // ev.preventDefault();
            });
            odiv.addEventListener('drop', function (ev) {
                console.log(ev.dataTransfer.files);
                console.log('你已经释放鼠标了');
                ev.preventDefault();
            }, false)

        }
    </script>
</head>
<body>
<div class="container" id="container">
    请将文件拖拽到此处
</div>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/rickyctbu/p/9653220.html