拖动鼠标更改DIV高度

7/2/2021 Javascript

# 背景

如图所示,实现拖动更改高度。

如图所示

# 实现

添加一条线,用来控制拖动,鼠标拖动时,计算拖动距离更改 div 的高度。主要是通过 mousedown、mousemove、mouseup 等鼠标事件来实现。

<div id="drag-box">
    <div class="data-list" id="drag-top"></div>
    <!-- 辅助线(用于调整文本框高度) -->
    <div id="resize" class="resize-line" @mousedown="handleMouseDown"></div>
    <div class="data-list target-list" id="drag-down"></div>
</div>
1
2
3
4
5
6
#drag-box {
    height: 500px;
}
.data-list {
    overflow-y: scroll;
    border-bottom: 1px solid #e3e5eb;
    height: calc(50% - 4px);
    min-height: 65px;
}
.target-list {
    height: 50%;
    min-height: 65px;
}
.resize-line {
    height: 4px;
    cursor: move;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {MouseEvent} 鼠标事件
*/
handleMouseDown(event) {
    // 禁止用户选择网页中文字
    document.onselectstart = () => false
    // 禁止用户拖动元素
    document.ondragstart = () => false

    // 保存鼠标最后移动的位置(Y轴)
    this.dragState = {
        // 鼠标开始移动的位置(Y轴)
        startMouseTop: event.clientY,
        // 鼠标最后移动的位置(Y轴)
        endMouseTop: event.clientY,
    }
    // 绑定鼠标移动事件
    document.addEventListener('mousemove', this.handleMouseMove)
    // 绑定鼠标放开事件
    document.addEventListener('mouseup', this.handleMouseUp)
},
/**
 * @param {MouseEvent} 鼠标事件
 */
handleMouseMove(event) {
    let dragBox = document.getElementById('drag-box')
    let dragTop = document.getElementById('drag-top')
    let dragDown = document.getElementById('drag-down')
    const { endMouseTop } = this.dragState
    // 计算鼠标移动的距离
    const distance = Math.abs(parseInt(((endMouseTop - event.clientY) * 100).toString(), 10) / 100)
    // 最小高度为60, 最大高度为第一次设置高度
    // 获取当前的文本框高度
    const topHeight = dragTop.getBoundingClientRect().height
    const downHeight = dragDown.getBoundingClientRect().height
    const boxHeight = dragBox.getBoundingClientRect().height
    // 若鼠标向上移动
    if (endMouseTop > event.clientY) {
        if (topHeight <= 65 || downHeight <= 65) return
        dragTop.style.height = topHeight - distance + 'px'
        dragDown.style.height = boxHeight - topHeight - distance - 5 + 'px'
    } else {
        // 若鼠标向下移动
        if (topHeight <= 65 || downHeight <= 65) {
            dragDown.style.height = '65px'
            return
        }
        dragTop.style.height = topHeight + distance + 'px'
        dragDown.style.height = boxHeight - topHeight - distance - 5+ 'px'
    }
    // 更新鼠标最后移动的位置(Y轴)
    this.dragState.endMouseTop = event.clientY
},
/**
 * 处理鼠标放开事件
 */
handleMouseUp() {
    // 移除鼠标移动事件
    document.removeEventListener('mousemove', this.handleMouseMove)
    // 移除鼠标放开事件
    document.removeEventListener('mouseup', this.handleMouseUp)
    // 允许用户选择网页中文字
    document.onselectstart = null
    // 允许用户拖动元素
    document.ondragstart = null
},
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
上次更新: 7/5/2021, 10:38:21 AM