vue2.0 scrollBar组件-鼠标拖动元素控制大小组件

此组件以vue2为基础的demo,源码放在最后,可以直接复制到index.html文件运行

在这里插入图片描述
首先是鼠标控制交互,用绝对定位把一个元素放到拖动的的位置,设置css属性:

cursor: col-resize;

剩下的也简单了,监听鼠标位置,记录上次鼠标位置,计算出移动的x轴距离或者y轴距离
直接上代码,剩下的可以自己搞成vue2组件,代码较少,改成vue3或react等框架也比较简单

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .body {
        display: flex;
        align-items: stretch;
        height: 300px;
    }

    .left {
        min-width: 100px;
        width: 120px;
        max-width: 300px;
        border: 1px solid #999;
        position: relative;
        background: #999;
    }

    .bar {
        display: inline-block;
        width: 10px;
        height: 100%;
        position: absolute;
        background: blue;
        right: -5px;
        top: 0;
        cursor: col-resize;
    }

    .right {
        flex-grow: 1;
        border: 1px solid #999;
        background: #ccc;
    }
</style>

<body>
    <div class="body" id="app">
        <div class="left" :style="{width:`${leftWidth}px`}">
            左
            <div class="bar" ref="bar"></div>
        </div>
        <div class="right">右</div>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
    const app = new Vue({
        el: "#app",
        data() {
            return {
                left: 0,    //组件控制横坐标
                leftWidth: 120,//左边bar默认宽度
                isControl: false,//正在控制鼠标
            }
        },
        created() {
            this.$nextTick(() => {
                this.$refs.bar.onmousedown = () => {
                    document.onmousedown = (e) => {
                        this.isControl = true
                        this.left = e.clientX
                    }
                    document.onmousemove = (e) => {
                        //鼠标点击后进入控制模式
                        if (this.isControl) {
                            this.leftWidth = e.clientX - this.left + this.leftWidth //改变bar宽度
                            this.left = e.clientX   //更新旧坐标
                        }
                    };
                    document.onmouseup = () => {
                        this.isControl = false
                        console.log('抬起鼠标,拖拽结束了')
                        // 拖拽结束执行一些方法
                    };
                };
            })
        }
    })
</script>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值