基于vue手写一个分屏器,通过鼠标控制屏幕宽度。

基于vue手写一个分屏器,通过鼠标控制屏幕宽度。

先来看看实现效果:

QQ录屏20220403095856

下面是实现代码:

<template>
  <section class="section">
    <div class="left"  ref="left">
        这是左边的div
        <div class="box" ref="box"></div>
    </div>
    <div class="right" ref="right">
        这是右边的div
    </div>
  </section>
</template>

<script>
export default {
  name: 'Test',
  mounted() {
    this.init()
  },
  methods: {
    init() {
      let left = this.$refs.left
      let right = this.$refs.right
      let box = this.$refs.box
      // firstX鼠标开始坐标位置,endX鼠标结束坐标位置,startWidth左边div开始宽度
      let firstX, endX, startWidth
      function myFunction(e) {
        // 划过左边线
        endX = e.clientX - firstX
        // 获取移动的距离
        left.style.width = startWidth + endX + 'px'
      }
      function selectStart(flag) {
        left.onselectstart = function() {
          return flag
        }
        right.onselectstart = function() {
          return flag
        }
      }

      box.addEventListener('mousedown',function(e) {
        // 当鼠标点击移动开始不选中div里的内容
        selectStart(false)
        startWidth = left.offsetWidth // 起始宽
        firstX = e.clientX // 起始点
        document.addEventListener('mousemove',myFunction) // 开始移动
      })
      box.addEventListener('mouseleave',function(e) {
        document.removeEventListener("mousemove", myFunction) // 结束移动
      })
      
      document.addEventListener('mouseup', function() {
        // 当鼠标点击移动结束恢复选中div里的内容
        selectStart(true)
        // 移除移动事件,注意:移除事件的回调函数必须和注册事件是同一个,要不然移除不了哦!
        document.removeEventListener("mousemove", myFunction) // 结束移动
      })
    }
  }
}
</script>
<style lang="scss" scoped>
        * {
            margin: 0;
            padding: 0;
        }
        .section {
          width: 100%;
          height: 100%;
          display: flex;
        }
       
        div.right {
            background-color: #00B83F;
            height: 100%;
            flex: 1;
        }

        div.left {
            width: 200px;
            background-color: #FFB951;
            z-index: 1;
            height: 100%;
            position: relative;
            .box {
              width: 50px;
              height: 50px;
              cursor: col-resize;
              background: red;
              position: absolute;
              right: 0;
              top: 0;
              bottom: 0;
              margin: auto;
            }
        }
</style>
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值