Vue练习六十一:08-03拖拽_bug版

  Demo浏览

说明:

1,使用了指令, v-drag

2,bug1,单击时,已经拖离初始位置的方块会弹回原位

3,bug2,点击时,左上角会出现一个方块的阴影

4,写指令时,发现指令中是无法访问data中的数据的

5,尝试使用v-if指令来动态生成/销毁移动时的阴影方块,则又涉及到如何向自定义指令传参及数据更改后如何让父组件中的对应数据更新,等等,暂时想不明白,先搁置一段时间,或许哪天就顿悟了!

6,刚才去超市买的兰花豆(三只松鼠)好难吃,浪费几块钱!再次感觉精疲力尽!一会冲个热水澡!

<template>
  <div id="app">
    <div id="drag1" v-drag @click="handleClick"></div>
    <div id="drag2" v-drag @click="handleClick"></div>  

  </div>
</template>
<script>
function getStyle(obj, attr)
{
    return parseFloat(obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr])
}
var zIndex = 1;

export default {
  data(){
    return{
      
    }
  },
  directives:{
    drag:{
      bind(el){          
        var disX = 0;
        var disY = 0;        
        
        el.onmousedown=function(e){
          disX = e.clientX - el.offsetLeft;
          disY = e.clientY - el.offsetTop; 
          
          var oTemp = document.createElement("div");
          oTemp['id']='temp';
          oTemp.style.left = getStyle(el,"left");
          oTemp.style.top = getStyle(el,"top");
          oTemp.style.zIndex = zIndex++;
          el.parentNode.appendChild(oTemp);

          

          document.onmousemove=function(e){
            var iL = e.clientX - disX;
            var iT = e.clientY - disY;
            var maxL = document.documentElement.clientWidth - el.offsetWidth;
            var maxT = document.documentElement.clientHeight - el.offsetHeight;

            iL <= 0 && (iL = 0);
            iT <= 0 && (iT = 0);
            iL >= maxL && (iL = maxL);
            iT >= maxT && (iT = maxT);

            oTemp.style.left = iL + 'px';
            oTemp.style.top = iT + 'px';
            return false;
          };
          document.onmouseup=function(){
            document.onmousemove=null;
            document.onmouseup = null;
            el.style.left = oTemp.style.left;
            el.style.top = oTemp.style.top;
            el.style.zIndex = oTemp.style.zIndex;
            
            el.parentNode.removeChild(oTemp);
            el.onclick=function(e){
              (e||window.event).cancelBubble = true;
            }

            el.releaseCapture && el.releaseCapture();
          };
          el.setCapture && el.setCapture();
          return false;
        }
      },

    }
  },
  methods:{
    handleClick(e){
      (e||window.event).cancelBubble=true;
    }
  },
  
}
</script>
<style>
body,div{
  margin: 0;
  padding: 0;
}
body{
  background: #3e3e3e;
}
#drag1, #drag2, #temp{
  position: absolute;
  width: 100px;
  height: 100px;
  cursor: move;
  border: 1px solid #888;
  background: #000;
}

#drag1{
  top:100px;
  left: 100px;
}
#drag2{
  top:100px;
  left: 300px;
}
#temp{
  opacity: 0.3;
  filter: alpha(opacity=30);
}
</style>

 

posted @ 2020-05-21 20:56  sx00xs  阅读(202)  评论(0编辑  收藏  举报