• 2019.9.4拖拽事件


    拖拽事件一共分为7种:

    在开始移动的时候触发ondragstart

    在移动中触发ondrag

    拖拽结束的事件ondragend

    拖拽元素进入目标元素时触发ondragenter

    在目标元素中移动中ondragover

    离开目标元素时触发ondragleave

    鼠标松开时触发ondrop

    拖拽的声明周期:
    1、拖拽开始
    2、拖拽进行中
    3、拖拽结束
    拖拽的组成
    被拖拽的物体
    目标区域

    下面我们来用代码以便更好的观察拖拽事件的各个阶段

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>拖拽--API</title>
    <style>
    body{
    margin: 0;
    }
    .draggable-box{
    100px;
    height: 100px;
    background-color: #abcdee;
    position: absolute;
    margin-top: 10px;
    margin-left: 20px;
    }
    .target{
    200px;
    height: 200px;
    border: 1px solid black;
    margin: 10px auto;
    }
    </style>
    </head>
    <body>
    <!-- chrome Safari 正常使用,Firefox部分浏览器支持 -->
    <div class="draggable-box" draggable = "true" ></div>
    <div class="target"></div>
    <!-- 默认可拖拽的标签 -->
    <!-- <a href="#">超链接aaa</a>
    <img src="imgs/bg.jpg" alt=""> -->
    <script>

    var oDragDiv = document.getElementsByClassName("draggable-box")[0];

    /*
    拖拽的声明周期:
    1、拖拽开始
    2、拖拽进行中
    3、拖拽结束
    拖拽的组成
    被拖拽的物体
    目标区域
    */
    // 在开始移动的时候触发
    var beginX = 0,beginY = 0;
    oDragDiv.ondragstart = function (e) {
    //鼠标距离元素边框的距离
    beginX = e.offsetX;
    beginY = e.offsetY;
    // console.log(beginX,beginY);
    // e.dataTransfer.effectAllowed = "copyMove";//copy move copyMove all
    }
    oDragDiv.ondrag = function (e) {
    //在移动中触发
    // console.log('在移动中触发了')
    }
    // 拖拽结束的事件
    oDragDiv.ondragend = function (e) {
    // console.log(e.clientX,e.clientY);
    var x = e.clientX - beginX;
    var y = e.clientY - beginY;

    // oDragDiv.style.left = x + "px";
    // oDragDiv.style.top = y + "px" ;
    console.log('over');
    }

    //目标元素的事件
    var oDragTarget = document.getElementsByClassName('target')[0]
    oDragTarget.ondragenter = function (e) {
    // 拖拽元素进入目标元素时触发
    // 注意:只有鼠标进入时才触发
    // console.log(e);
    }
    oDragTarget.ondragover = function(e) {
    // 在目标元素中移动中
    // console.log(e);
    e.dataTransfer.effectAllowed = "copyMove";
    //阻止直接触发拖拽事件的结束
    e.preventDefault();
    }
    //离开目标元素时触发
    oDragTarget.ondragleave = function (e) {
    // console.log(e);
    console.log('leave')
    }
    // 移动的元素从目标元素中离开以后触发
    /*
    ondrop这个行为触发了两个事件 回到原处 离开目标元素 ---链模式 a - b/c
    */
    // 鼠标松开时触发
    oDragTarget.ondrop = function (e) {
    // console.log(e)
    console.log('ondrop');
    }
    </script>
    </body>
    </html>

  • 相关阅读:
    eclipse tomcat插件
    eclipse.ini
    iBatis杂记
    oracle 10g express 下载网址
    免费ftp客户端 winscp
    maven web app 发布到Tomcat
    sqlserver获取本月最后一天
    ArrayCollection和ComboBox
    flex框架 Cairngorm
    HDU3420 Bus Fair
  • 原文地址:https://www.cnblogs.com/awei313558147/p/11574757.html
Copyright © 2020-2023  润新知