• 拖拽


     1 <!DOCTYPE html>
     2 <html>
     3     <head>
     4         <meta charset="UTF-8">
     5         <title>拖拽</title>
     6         <style>
     7             #div1{
     8                 width: 200px;
     9                 height: 200px;
    10                 background: red;
    11                 position: absolute;
    12             }
    13             #div1:hover{
    14                 cursor: pointer;
    15             }
    16         </style>
    17     </head>
    18     <body>
    19         <div id="div1"></div>
    20         <script>
    21             var oDiv = document.getElementById('div1');
    22             
    23             var disX = 0;    //鼠标的横向距离
    24             var disY = 0;     //鼠标的纵向距离
    25             
    26             oDiv.onmousedown = function(ev){
    27                 var oEvent = ev || event;
    28                 disX = oEvent.clientX - oDiv.offsetLeft;
    29                 disY = oEvent.clientY - oDiv.offsetTop;
    30                 
    31                 document.onmousemove = function(ev){
    32                     var oEvent = ev || event;
    33                     var l = oEvent.clientX - disX;
    34                     var t = oEvent.clientY - disY;
    35                     
    36                     if(l<0){   //div从左边被拖出去
    37                         l = 0;
    38                     }else if(l > document.documentElement.clientWidth - oDiv.offsetWidth){
    39                         l = document.documentElement.clientWidth - oDiv.offsetWidth;
    40                     }
    41                     if(t<0){   //div从上边被拖出去
    42                         t = 0;
    43                     }else if(t>document.documentElement.clientHeight - oDiv.offsetHeight){
    44                         t = document.documentElement.clientHeight - oDiv.offsetHeight;
    45                     }
    46                     
    47                     //根据最新的鼠标坐标来确定div的坐标
    48                     oDiv.style.left = l + 'px';
    49                     oDiv.style.top = t + 'px';
    50                 }
    51                 
    52                 document.onmouseup = function(ev){
    53                     document.onmousemove = null;
    54                     document.onmouseup = null;
    55                 }
    56                 
    57                 //解决火狐拖拽的bug,取消默认事件
    58                 return false;
    59             }
    60         </script>
    61     </body>
    62 </html>
  • 相关阅读:
    4815 江哥的dp题a
    CON1023 明明的计划
    5200 fqy的难题----2的疯狂幂
    [SCOI2005] 最大子矩阵
    1457 又是求和?
    2064 最小平方数
    vijos P1459车展
    1366 xth 的第 12 枚硬币
    1360 xth 的玫瑰花
    3223: Tyvj 1729 文艺平衡树
  • 原文地址:https://www.cnblogs.com/panda-ling/p/6699963.html
Copyright © 2020-2023  润新知