JS实现拖拽改变div的宽度(v1)

2,884 阅读1分钟

直接上代码吧

注:代码仅供参考提供思路,可能并不适用于你的业务场景。

代码上实现起来比较简单,大概讲一下实现流程吧。

这种简单的拖动改变div宽度的功能,是要有一个button作为切入口(触发方法)的,也最好是使用button标签,因为div标签会有拖拽选中变蓝的问题。

通过按下button按钮,给document增加一个mousemove事件来获取当前的坐标,再将坐标通过计算之后得到合法的宽度值(坐标有可能会得到负数在拖动超出浏览器外的情况下)。

得到我们想要的值就直接改变盒子的宽度就好了。

以上说的都是废话,因为不超过50字不能发布,直接复制下面代码自己运行就可以了。


可以直接复制到html文件中运行。
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        main{width:300px;position:fixed;right:0;bottom:0;top:0;background-color:#ccc;}
        .box{position:relative;height:100%}
        button{position:absolute;left:0;top:0;bottom:0;width:20px;background-color:pink}
    </style>
</head>
<body>
    
    <main>
        <div class="box">
            <button></button>
        </div>
    </main>

    <script>
        (function(){
            const fixedWidth = document.querySelector('main').offsetWidth
            function documentMove(e){
                const w = document.documentElement.offsetWidth-e.x
                if(w>fixedWidth && w<document.documentElement.offsetWidth - fixedWidth){
                    document.querySelector('main').style.width=w+'px'
                }
            }
            document.querySelector('button').addEventListener('mousedown',()=>{
                document.addEventListener('mousemove',documentMove)
            })

            document.addEventListener('mouseup',()=>{
                document.removeEventListener('mousemove',documentMove)
            })
        })()


    </script>
</body>
</html>