zoukankan      html  css  js  c++  java
  • 拖拽

     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>
  • 相关阅读:
    HTTP学习笔记(1)ULR语法
    wsdl地址如何在远程服务器上查看源码?
    java线程详解(三)
    java线程详解(二)
    java线程详解(一)
    java中this用法总结
    Linux运行python程序
    如何获取到Java对象的地址
    IDEA 远程调试
    linux环境中mysql默认端口3306无法连接问题排查
  • 原文地址:https://www.cnblogs.com/panda-ling/p/6699963.html
Copyright © 2011-2022 走看看