wujingjing
2024-11-14 6e3dff485788426e94b7fad0edb1717e3f0c9f40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import _ from 'lodash';
import { ref } from 'vue';
 
export type UseDragSideOption = {
    maxWidth: number;
    minWidth: number;
    defaultWidth: number;
};
 
export const useDragSidebar = (option?: Partial<UseDragSideOption>,cb?:Function) => {
    const { maxWidth, minWidth, defaultWidth } = _.defaults(option, {
        maxWidth: Infinity,
        minWidth: 120,
        defaultWidth: 300,
    } as UseDragSideOption);
    const resizeRef = ref<HTMLDivElement>(null);
    const draggableWidth = ref(defaultWidth);
 
    const dragControllerDiv = () => {
        const resize = resizeRef.value;
        resize.onmousedown = function (e) {
            // 颜色改变提醒
            resize.style.background = '#818181';
            let startX = e.clientX;
            (resize as any).left = resize.offsetLeft;
            document.onmousemove = function (e) {
                // 计算并应用位移量
                const endX = e.clientX;
                const moveLen = endX - startX;
                startX = endX;
                if ((draggableWidth.value > maxWidth && moveLen < 0) || (draggableWidth.value < minWidth && moveLen > 0)) {
                    return;
                }
                cb?.();
                draggableWidth.value -= moveLen;
            };
            document.onmouseup = function () {
                // 颜色恢复
                resize.style.background = '';
                document.onmousemove = null;
                document.onmouseup = null;
            };
            return false;
        };
    };
 
    return {
        dragControllerDiv,
        resizeRef,
        draggableWidth,
    };
};