其他分享
首页 > 其他分享> > js draggable 拖拽

js draggable 拖拽

作者:互联网

<body>
    <div id="wrapper">
        <div class="dropzone">
            <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)">
                This div is draggable
            </div>
        </div>
        <div class="dropzone"></div>
        <div class="dropzone"></div>
        <div class="dropzone"></div>
    </div>

    <style>
        #draggable {
            width: 200px;
            height: 20px;
            text-align: center;
            background: lightcoral;
        }

        .dropzone {
            width: 200px;
            height: 20px;
            background: aqua;
            margin-bottom: 10px;
            padding: 10px;
        }
    </style>

    <script>
        var dragged;
        const wDom = document.getElementById('wrapper')
        // drag,dragover在拖起的时候会持续触发
        /* 拖动目标元素时触发 drag 事件 */
        wDom.addEventListener("drag", function (event) {
            // console.log('触发拖动');
        }, false);

        wDom.addEventListener("dragstart", function (event) {
            console.log('开始拖动');
            // 保存拖动元素的引用 (ref.)
            dragged = event.target;
            // 使其半透明
            event.target.style.opacity = .5;
        }, false);

        wDom.addEventListener("dragend", function (event) {
            console.log('结束拖动');
            // 重置透明度
            event.target.style.opacity = "";
        }, false);

        /* 放置目标元素时触发事件 */
        wDom.addEventListener("dragover", function (event) {
            // console.log('悬浮拖动');
            // 阻止默认动作以启用 drop
            event.preventDefault();
        }, false);

        wDom.addEventListener("dragenter", function (event) {
            console.log('拖入');
            // 当可拖动的元素进入可放置的目标时高亮目标节点
            if (event.target.className == "dropzone") {
                event.target.style.background = "lightcoral";
            }
        }, false);

        wDom.addEventListener("dragleave", function (event) {
            console.log('拖离,离开目标节点');
            // 当拖动元素离开可放置目标节点,重置其背景
            if (event.target.className == "dropzone") {
                event.target.style.background = "";
            }

        }, false);

        wDom.addEventListener("drop", function (event) {
            console.log('放置');
            // 阻止默认动作(如打开一些元素的链接)
            event.preventDefault();
            // 将拖动的元素到所选择的放置目标节点中
            if (event.target.className == "dropzone") {
                event.target.style.background = "";
                dragged.parentNode.removeChild(dragged);
                event.target.appendChild(dragged);
            }

        }, false);
    </script>
</body>

标签:false,target,拖动,wDom,拖拽,draggable,js,event,log
来源: https://www.cnblogs.com/ltfxy/p/16386050.html