參考地址:基於Vue實現拖拽效果
參考鏈接中講的比較詳細,我只使用了其中自定義指令的方法。整體代碼如下:
<template> <!-- 卡片 --> <div class="card" v-drag id="card"> </div> </template> <script> export default { data() { return { } }, directives: { drag: { // 指令的定義 bind: function(el) { let oDiv = el; // 獲取當前元素 oDiv.onmousedown = (e) => { // 算出鼠標相對元素的位置 let disX = e.clientX - oDiv.offsetLeft; let disY = e.clientY - oDiv.offsetTop; document.onmousemove = (e) => { // 用鼠標的位置減去鼠標相對元素的位置,得到元素的位置 let left = e.clientX - disX; let top = e.clientY - disY; oDiv.style.left = left + 'px'; oDiv.style.top = top + 'px'; }; document.onmouseup = (e) => { document.onmousemove = null; document.onmouseup = null; } } } } } } </script> <style lang="scss"> .card { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 870px; height: 510px; background-color: #3ab5a0; } </style>
使用方法:在需拖拽功能的元素上添加v-drag啟用:
補充:阻止拖拽
上述方法利用自定義指令實現了彈窗的拖拽,補充部分是阻止拖拽,例如:彈窗中有input框,如果想要選中input中的內容就需要阻止彈窗的拖拽
參考地址:vue實現彈窗拖拽
export default { directives: { /*自定義拖拽*/ drag: { inserted: function(el, binding, vnode) { var odiv = el.parentNode; odiv.onmousedown = function(eve) { eve = eve || window.event; var clientX = eve.clientX; var clientY = eve.clientY; var odivX = odiv.offsetLeft; var odivY = odiv.offsetTop; var odivLeft = clientX - odivX; var odivTop = clientY - odivY; var clientWidth = document.documentElement.clientWidth; var oWidth = odiv.clientWidth; var odivRight = clientWidth - oWidth; var clientHeight = document.documentElement.clientHeight; var oHeight = odiv.clientHeight; var odivBottom = clientHeight - oHeight; document.onmousemove = function(e) { e.preventDefault(); var left = e.clientX - odivLeft; if (left < 0) { left = 0 } if (left > odivRight) { left = odivRight } var Top = e.clientY - odivTop; if (Top < 0) { Top = 0 } if (Top > odivBottom) { Top = odivBottom } odiv.style.left = left + "px"; odiv.style.top = Top + "px"; } document.onmouseup = function() { document.onmouseup = ""; document.onmousemove = ""; } } } }, /*阻止拖拽*/ stopdrag: { inserted: function(el, binding, vnode) { let element = el; element.onmousedown = function(e) { e.stopPropagation() } } } } }
使用方法:在不需拖拽的元素上添加v-stopdrag阻止: