vue前端元素任意拖拽效果-解决拖拽有时失效问题、不能快速拖拽问

2021-04-25  本文已影响0人  who_are_you_

vue - main.js文件

// 在vue  main.js文件中加上这个,然后就可以使用vue的快捷指令
Vue.directive("drag", {
  inserted: function(el){
      let odiv = el;   //获取当前元素
      odiv.onmousedown = (e) => {
          //算出鼠标相对元素的位置
          let disX = e.clientX - odiv.offsetLeft;
          let disY = e.clientY - odiv.offsetTop;
          // 为什么用document:如果绑定到元素本身的情况下,鼠标拖动过快,鼠标会离开拖拽的元素,导致拖拽一段距离,拖拽失效的问题
          document.onmousemove = (e)=>{
              //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
              let left = e.clientX - disX;
              let top = e.clientY - disY;
              //绑定元素位置到positionX和positionY上面
              // this.positionX = top;
              // this.positionY = left;
              let FWidth = el.parentNode.offsetWidth - el.offsetWidth;
              let FHeight = el.parentNode.offsetHeight - el.offsetHeight;
              //移动当前元素
              // console.log('left' + left);
              // console.log('top' + top);
              // 判断当前元素可以活动的区域
              if (left <= 0) {
                odiv.style.left = 0 + 'px';
              } else if (left >= FWidth) {
                odiv.style.left = FWidth + 'px';
              } else if (left > 0) {
                odiv.style.left = left + 'px';
              }
              if (top <= 0) {
                odiv.style.top = 0 + 'px';
              } else if (top >= FHeight) {
                odiv.style.top = FHeight + 'px';
              }  else if (top > 0) {
                odiv.style.top = top + 'px';
              }
          };
          document.onmouseup = (e) => {
              document.onmousemove = null;
              document.onmouseup = null;
          };
      };
  }
});

vue文件使用:

<template>
<div style="width: 100%; position: relative; height: 500px;border: 1px solid; overflow: hidden; box-sizing: border-box;" >
            <div :style="{width: '100px', height: '40px',border: '1px solid',position: 'absolute', zIndex: 2000 + index,left: index *110 + 'px', top: '10px'} " class="shape" v-drag v-for='(item, index) in 4' :key='index'>
            {{index}}
            </div>
            <div style="width: 100%; height: 440px; border: 1px solid; margin-top: 60px;">
            </div>
 </div>
</template>
<style lang='scss' scoped>
// 设置元素不可复制 解决了拖动时会拖掉的问题
.shape {
    -moz-user-select:none; /* Firefox私有属性 */
    -webkit-user-select:none; /* WebKit内核私有属性 */
    -ms-user-select:none; /* IE私有属性(IE10及以后) */
    -khtml-user-select:none; /* KHTML内核私有属性 */
    -o-user-select:none; /* Opera私有属性 */
    user-select:none; /* CSS3属性 */
}
</style>
上一篇 下一篇

猜你喜欢

热点阅读