vue div拖拽


  在前端開發中,拖拽是非常常見的一種方式,但是之前感覺拖拽實現起來比較麻煩,一直未深入研究,現在整理了幾個實現方式:

1、原生方式

html部分

1 <div class="div" v-drag ></div> 

 

js部分

 1 methods:{},
 2     directives: {
 3         drag: {
 4             // 指令的定義
 5             bind: function (el) {
 6                 let odiv = el;   //獲取當前元素
 7                 el.onmousedown = (e) => {
 8                     //算出鼠標相對元素的位置
 9                     let disX = e.clientX - odiv.offsetLeft;
10                     let disY = e.clientY - odiv.offsetTop;
11                     let left = '';
12                     let top = '';
13                     document.onmousemove = (e)=>{
14                         //用鼠標的位置減去鼠標相對元素的位置,得到元素的位置
15                         left = e.clientX - disX;    
16                         top = e.clientY - disY;
17                         //綁定元素位置到positionX和positionY上面
18                         //移動當前元素
19                         odiv.style.left = left + 'px';
20                         odiv.style.top = top + 'px';
21                     };
22                     document.onmouseup = (e) => {
23                         document.onmousemove = null;
24                         document.onmouseup = null;
25                     };
26                 };
27             }
28         }
29     }

 

2、vue 組件 vue-drag-resize 

 vue-drag-resize 這個組件不但能夠實現拖拽功能,還可以實現縮放功能。

加載:

npm i -s vue-drag-resize

使用:

 <template>
     <div id="app">
          <vue-drag-resize></vue-drag-resize>
     </div>
  </template>
  import VueDragResize from 'vue-drag-resize';
  export default {
      name: 'app',
      components: {
          VueDragResize
      },
  }        

詳細參數及方法介紹可參考文檔 https://www.npmjs.com/package/drag-resize-vue 或博客https://blog.csdn.net/weixin_33957648/article/details/91423751


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM