zoukankan      html  css  js  c++  java
  • javascript 拖拽

    拖拽分为三个部分:

    1.mousedown:

    •  获取鼠标当前位置,e.clientX,e.clientY
    •  获取拖动物体的位置(距离左上角),_this.offsetLeft,_this.offsetTop
    • 代码:
      1 dragDivName.onmousedown=function(e){
      2         var e = getEvent(e);//[object MouseEvent]
      3         var _this = this;//[object HTMLDivElement]
      4         var diffX = e.clientX - _this.offsetLeft;//获取鼠标当前点距离最近容器的左边距离
      5         var diffY = e.clientY - _this.offsetTop;//获取鼠标当前点距离最近容器的上面距离
      6         //鼠标锁住时触发(点击住),IE兼容性
      7         if (typeof _this.setCapture != 'undefined') {
      8             _this.setCapture();
      9         }

    2.mousemove:

    • 因为是在整个页面可以滑动,所以事件对象应该为document
    • 获取移动后鼠标的位置
    • 根据mousedown计算出的鼠标位置与移动物体左上角的位置计算出现在物体应该在的位置
    • 对物体左边和上面位置进行判断,是否为负数
    • 给移动物体位置赋值
    • 代码
       1 document.onmousemove = function (e) {
       2             var e = getEvent(e);
       3             var left = e.clientX - diffX;//获取容器距离窗口左边的距离
       4             var top = e.clientY - diffY;//获取容器距离窗口上面的距离
       5             //对左边距离进行判断
       6             if (left < 0) {
       7                 left = 0;
       8             } else if (left > getInner().width - _this.offsetWidth) {
       9                 left = getInner().width - _this.offsetWidth;
      10 
      11             }
      12             //对上面距离进行判断
      13             if (top < 0) {
      14                 top = 0;
      15             } else if (top > getInner().height - _this.offsetHeight) {
      16                 top = getInner().height - _this.offsetHeight;
      17             }
      18             //对容器位置进行赋值
      19             _this.style.left = left + 'px';
      20             _this.style.top = top + 'px';
      21 
      22         }

    3.mouseup:

    • 释放鼠标的操作
    • 代码:
      1 document.onmouseup = function () {
      2             this.onmousemove = null;
      3             this.onmouseup = null;
      4             //鼠标释放时触发(放开鼠标),IE兼容性
      5             if (typeof _this.releaseCapture != 'undefined') {
      6                 _this.releaseCapture();
      7             }
      8         }
  • 相关阅读:
    [BZOJ1625][Usaco2007 Dec]宝石手镯
    [BZOJ1699][Usaco2007 Jan]Balanced Lineup排队
    [BZOJ1606][Usaco2008 Dec]Hay For Sale 购买干草
    [BZOJ1610][Usaco2008 Feb]Line连线游戏
    [BZOJ1609][Usaco2008 Feb]Eating Together麻烦的聚餐
    [BZOJ1602][Usaco2008 Oct]牧场行走
    [BZOJ1601][Usaco2008 Oct]灌水
    [BZOJ1607][Usaco2008 Dec]Patting Heads 轻拍牛头
    [BZOJ1579][Usaco2008 Mar]土地购买
    HDU 4248 A Famous Stone Collector 组合数学dp ****
  • 原文地址:https://www.cnblogs.com/qiangmin/p/4024826.html
Copyright © 2011-2022 走看看