zoukankan      html  css  js  c++  java
  • 拖拽

         今天来说下  拖拽效果,纯手工。下面会有代码和注释。

    首先,要想能拖动div就考虑到三个事件,鼠标按下  鼠标拖动   鼠标松开。

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    <style>
    /*给div来些样式 最主要的是绝对定位*/
    #dIv{
    100px;
    height: 100px;
    background: red;
    position: absolute;
    }
    </style>
    </head>
    <body>
    <div id="dIv"></div>
    <script>
    //获取我们的div
    var dIv = document.getElementById("dIv");
    //鼠标按下 获取event事件
    dIv.onmousedown=function(e){
    var e = event || window.event;
    //dis 指的是鼠标的当前位置 减去 div距离屏幕左边的距离 也就是鼠标的位置距离到div左外边框的位置
    var dis = e.clientX - dIv.offsetLeft;
    //dir 指的是鼠标的当前位置 减去div距离屏幕上边的距离 也就是鼠标的位置距离到div上外边框的位置
    var dir = e.clientY - dIv.offsetTop;
    //鼠标移动事件
    document.onmousemove=function(e){
    var e = event || window.event;
    //l 就是div要左右移动的距离 拖动时鼠标的位置减去 dis
    var l = e.clientX-dis;
    //x 就是div要上下移动的距离 拖动时鼠标的位置减去 dir
    var x = e.clientY-dir;
    dIv.style.left=l+"px";
    dIv.style.top=x+"px";
    //鼠标松开事件 鼠标松开时
    document.onmouseup=function(){
    //把鼠标按下事件 和移动事件 清除 为零
    document.onmousedown=null;
    document.onmousemove=null;
    }
    }
    }
    </script>
    </body>
    </html>

  • 相关阅读:
    POJ 2031 Building a Space Station
    [Codeforces 623A] Graph and String
    [Codeforces 986E] Prince's Problem
    [Codeforces 496E] Distributing Parts
    [Codeforces 1037E] Trip
    [Codeforces 1037D] Valid BFS?
    [Codeforces 666B] World Tour
    [Codeforces 449B] Jzzhu and Cities
    [Codeforces 475B] Strongly Connected City
    [Codeforces 437C] The Child and Toy
  • 原文地址:https://www.cnblogs.com/Rzyy/p/7015622.html
Copyright © 2011-2022 走看看