html拖拽事件

需要先设置拖拽元素的draggable属性为true。
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        li {
            list-style: none;
            float: left;
            width: 50px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            border-radius: 50%;
            background-color: yellow;
        }

        .a,
        .b {
            width: 300px;
            height: 300px;
            border: 1px solid red;
        }
    </style>
</head>
<body>
<ul class="a">
    <li draggable="true">1</li>
    <li draggable="true">2</li>
    <li draggable="true">3</li>
    <li draggable="true">4</li>
</ul>
<div class="b">
</div>

<!--javascript-->
<script>
    var lis = document.querySelectorAll("li");
    var b = document.querySelector(".b");
    var srcEle;
    lis.forEach(function (element, index) {
                //拖动就会触发
//                element.ondrag = function () {
//                    console.log("拖拽元素drag");
//                }
                //拖动开始的时候
                element.ondragstart = function () {
                    srcEle = index;
                    console.log("拖拽元素dragstart");
                }
                //离开自己的时候
                element.ondragleave = function () {
                    console.log("拖拽元素dragleave");
                }
                //手放下的那一刻
                element.ondragend = function () {
                    console.log("拖拽元素dragend");
                }
            }
    )

    //拖动元素时,鼠标进入目标元素后会触发一次!
    b.ondragenter = function () {
        console.log("目标元素ondragenter");
    }

    //拖动元素时,鼠标进入目标元素后会一直触发
    b.ondragover = function (e) {
        e = e || window.event;
        e.preventDefault();
        console.log("目标元素ondragover");
    }
    b.ondragleave = function () {
        console.log("目标元素ondragleave");
    }
    //拖动元素在目标元素上面放下的时候触发
    b.ondrop = function () {
        this.appendChild(lis[srcEle]);
        console.log("目标元素ondrop");
    }
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值