js腳本
export function dragBox(drag, wrap) {
// 用于擷取父容器的樣式屬性值
function getCss(ele, prop) {
// getComputedStyle傳回值是帶機關的字元串,是以得parseInt
return parseInt(window.getComputedStyle(ele)[prop]);
}
// 滑鼠點選位置的螢幕x,y坐标
let initX;
let initY;
// 父容器的螢幕x,y坐标
let wrapLeft;
let wrapRight;
// 用于判斷滑鼠按住與松開
let dragable = false;
// 給子容器綁定mousedown事件
drag.addEventListener(
"mousedown",
function (e) {
dragable = true;
wrapLeft = getCss(wrap, "left");
wrapRight = getCss(wrap, "top");
initX = e.clientX;
initY = e.clientY;
},
false
);
// 給子容器綁定mouseup事件
drag.addEventListener(
"mouseup",
function (e) {
dragable = false;
},
false
);
// 頁面綁定mousemove事件
document.addEventListener("mousemove", function (e) {
if (dragable === true) {
let nowX = e.clientX;
let nowY = e.clientY;
let disX = nowX - initX;
let disY = nowY - initY;
wrap.style.left = wrapLeft + disX + "px";
wrap.style.top = wrapRight + disY + "px";
}
});
}
vue頁面使用
<template>
<div id="father">
<div id="son"/>
......
</div>
</template>
<script>
import { dragBox } from '@/utils/controls'
export default {
.....
mounted(){
this.$nextTick(()=>{
dragBox(document.querySelector('.son'),document.querySelector('#father'))
})
},
......
}
</script>
<style>
#father{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 15px;
#son{
cursor: move;
}
......
}
</style>
注意這裡的函數會形成閉包,變量會一直儲存在記憶體