vue 拖拽div 自定义div拖拽

js 可拖拽div内容框记录

1、css样式

.dragDrop{width:220px;height:88px;line-height:88px;text-align: center;background: #fff;border-radius: 5px;position: fixed;z-index: 9999;bottom: 8%;left: 5%;box-shadow: 0 0 6px 0 #ff5722;cursor:move;}
.dragDrop>a{width: 140px;height:46px;line-height:46px;display: inline-block;border-radius: 35px;background: #ff5722;color: #fff;text-decoration: none;}
.dragDrop>a:active{background: #ff784e;}

一、静态html方法

1、html代码

// 方法一(html)

 2、js代码

// 方法一(js)
window.onload = function(){
  let box = document.getElementById("dragDrop"), l = 0, t = 0;
  // 鼠标按下执行
  box.onmousedown = function(e){
    l = e.clientX - box.offsetLeft;
    t = e.clientY - box.offsetTop;
    // 鼠标按住后移动到某处执行
    document.onmousemove = function(e){
      let x = e.clientX - l,
          y = e.clientY - t,
          w = document.documentElement.clientWidth,
          h = document.documentElement.clientHeight;
      if(x < 0){
        x = 0;
      }else if(x > w - box.offsetWidth){
        x = w - box.offsetWidth;
      }
      if(y < 0){
        y = 0;
      }else if(y > h - box.offsetHeight){
        y = h - box.offsetHeight;
      }
      // 对象赋予坐标
      box.style.left = x + "px";
      box.style.top = y + "px";
    }
    // 鼠标按键松开执行
    document.onmouseup = function(){
      document.onmousemove = null;
      document.onmouseup = null;
    }
    return false;
  }
}

二、vue方法

 1、dom设置

// 方法二(vue)

比较 {{dragDropNum}} 种物料

2、methods方法

// 方法二(vue)
dialogChange(e){
  let box = e.currentTarget;
      let l = 0, t = 0;
  // 鼠标按下执行
  box.onmousedown = function(e){
    l = e.clientX - box.offsetLeft;
    t = e.clientY - box.offsetTop;
    // 鼠标按住后移动到某处执行
    document.onmousemove = function(e){
      let x = e.clientX - l,
          y = e.clientY - t,
          w = document.documentElement.clientWidth,
          h = document.documentElement.clientHeight;
      if(x < 0){
        x = 0;
      }else if(x > w - box.offsetWidth){
        x = w - box.offsetWidth;
      }
      if(y < 0){
        y = 0;
      }else if(y > h - box.offsetHeight){
        y = h - box.offsetHeight;
      }
      // 对象赋予坐标
      box.style.left = x + "px";
      box.style.top = y + "px";
    }
    // 鼠标按键松开执行
    document.onmouseup = function(){
      document.onmousemove = null;
      document.onmouseup = null;
    }
    return false;
  }
}

三、对应文件内容(文件可直接下载)

可拖拽div内容框.rar-互联网文档类资源-CSDN下载

你可能感兴趣的:(前端,vue,element,js,javascript,css)