js拖拽改变元素高度

407 阅读1分钟

js原生 拖拽改变元素高度

小坑记!!!

效果图

image.png

初始版

存在问题

  1. 只能向下拖拽
  2. onmouseup事件监听不到

分析

给dragBar添加监听事件时,拖拽过程,鼠标会离开该元素,会造成mouseup,mousemove事件不是发生在该元素上,达不到拖拽效果,所以应该将事件绑定在window对象上才行。

代码

`

    <div class="container">
        <div class="drag-bar"  onmouseup="">
            <div class="line"></div>
            <div class="line"></div>
        </div>
    </div>
</body>
</html>
<script>
    const dragBar = document.getElementsByClassName('drag-bar')[0]
    const Container = document.getElementsByClassName('container')[0]
    let startX, startY
    //判断鼠标是否按下状态
    let isResizing = false
    dragBar.onmousedown = (e) => {
        startY = e.clientY
        isResizing = true
    }
    dragBar.onmousemove = (e) => {
        if(isResizing){
            Container.style.height = (window.innerHeight - e.clientY - dragBar.clientHeight) + 'px'
        }
        else{
            return
        }
    }
    dragBar.onmouseup = () => {
        dragBar.onmousedown = null
        dragBar.onmousemove = null
        isResizing = false
    }
</script>`

修改

代码

`<body>
    <div class="container">
        <div class="drag-bar"  onmouseup="">
            <div class="line"></div>
            <div class="line"></div>
        </div>
    </div>
</body>
</html>
<script>
    const dragBar = document.getElementsByClassName('drag-bar')[0]
    const Container = document.getElementsByClassName('container')[0]
    let startX, startY
    //判断鼠标是否按下状态
    let isResizing = false
    window.onmousedown = (e) => {
        startY = e.clientY
        isResizing = true
    }
    window.onmousemove = (e) => {
        if(isResizing){
            Container.style.height = (window.innerHeight - e.clientY - dragBar.clientHeight) + 'px'
        }
        else{
            return
        }
    }
    window.onmouseup = () => {
        window.onmousedown = null
        window.onmousemove = null
        isResizing = false
    }
</script>
<style>
    .container{
        width: 100%;
        height: 100px;
        background-color:rgb(201, 200, 200);
        position: fixed;
        left: 0;
        bottom: 0;
    }
    .drag-bar{
        width: 100%;
        height: 10px;
        background:rgb(128, 127, 127);
        cursor: ns-resize;
        position: relative;
        left: 0;
        top: 0;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
    }
    .line{
        width: 25px;
        height: 2px;
        background-color: white;
    }
</style>`