zoukankan      html  css  js  c++  java
  • JS事件中级 --- 拖拽

    http://bbs.zhinengshe.com/thread-1200-1-1.html

    要求:实现div块的拖拽

    原理:拖拽过程中鼠标点和div块的相对位置保持不变。

    需要理解三点:

    1. 为什么要把onmousemove,onmouseup加在document上面 ?

    2. onmouseup要怎么使用 ?

    3. 如何防止div块跑出边界 ?

     1 <!DOCTYPE html>
     2 <html>
     3 <head lang="en">
     4     <meta charset="UTF-8">
     5     <title></title>
     6     <style>
     7         #div1 {
     8             width: 200px;
     9             height: 200px;
    10             background-color: red;
    11             position: absolute;
    12         }
    13     </style>
    14     <script>
    15         window.onload = function () {
    16             var oDiv = document.getElementById("div1");
    17 
    18             var disX = 0;
    19             var disY = 0;
    20 
    21             oDiv.onmousedown = function (event) {
    22                 disX = event.clientX - oDiv.offsetLeft;
    23                 disY = event.clientY - oDiv.offsetTop;
    24 
    25                 document.onmousemove = function (event) {
    26 
    27                     var divLeft = event.clientX - disX;
    28                     var divTop = event.clientY - disY;
    29 
    30                     if (divLeft < 0) divLeft = 0;
    31                     if (divLeft > document.documentElement.clientWidth-oDiv.offsetWidth) {
    32                         divLeft = document.documentElement.clientWidth-oDiv.offsetWidth;
    33                     }
    34                     if (divTop < 0) divTop = 0;
    35                     if (divTop > document.documentElement.clientHeight - oDiv.offsetHeight) {
    36                         divTop = document.documentElement.clientHeight - oDiv.offsetHeight;
    37                     }
    38 
    39                     oDiv.style.left = divLeft + "px";
    40                     oDiv.style.top = divTop + "px";
    41                 };
    42                 document.onmouseup = function () {
    43                     document.onmousemove = null;
    44                     document.onmouseup = null;
    45                 }
    46             };
    47         }
    48     </script>
    49 </head>
    50 <body>
    51     <div id="div1"></div>
    52 </body>
    53 </html>
    View Code

    运行效果:【点击这里】

  • 相关阅读:
    c#+oracle存储过程实现分页
    C#中调用Matlab程序
    Oracle 自定义TYPE 的几种用法(转)
    oracle嵌套表示例
    矩阵的秩及矩阵的广义逆
    矩阵的定义及其运算规则
    矩阵微分
    matlab中取模(mod)与取余(rem)的区别
    hog源码分析
    矩阵的转置、求逆及分块
  • 原文地址:https://www.cnblogs.com/linxd/p/4565311.html
Copyright © 2011-2022 走看看