React 自定义 Antd 中 Drawer 组件实现鼠标拖拽控制长度(上下伸缩)

自定义实现控制鼠标伸缩 drawer 组件改变长度为例,直接上代码:

import React, { useState } from 'react';
import { Drawer } from 'antd';

import './resizableStyle.scss';

function Index() {
  const [open, setOpen] = useState(false);

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };

  /**
   * 实现上下拉伸 drawer
   * @param {*} e
   */
  const onmousedown = (e) => {
    // 获取 line
    const child = document.getElementById('line');
    if (child) {
      // 保存原始 drawer 高
      sessionStorage.setItem('drawerheight', child.style.height);
      const startY = e.clientY;
      window.onmousemove = function (e) {
        // 获取当前移动的 y
        const endY = e.clientY;
        const dragHei =
          startY - endY + parseInt(sessionStorage.getItem('drawerheight'));

        // 拖动节点的高
        child.style.height = `${dragHei}px`;

        // 改变 drawer 的高
        const endDraerHei = document.body.clientHeight - e.screenY;
        let handleHei;
        handleHei = `${endDraerHei}px`; // 默认值当前高度
        if (endDraerHei <= 200) handleHei = `${200}px`; // 往下拽的最小值
        if (endDraerHei > 800) handleHei = `${800}px`; // 往上拽的最大值
        document.getElementsByClassName('ant-drawer-content-wrapper')[0].style.height = handleHei;
      };
      window.onmouseup = () => {
        window.onmousemove = null;
        window.onmouseup = null;
      };
      child.releaseCapture && child.releaseCapture();
    }
  };
  return (
    <div>
      <div onClick={showDrawer}>打开抽屉</div>
      <Drawer
        rootClassName="drawer"
        className="drawer-container"
        title="drawerTitle"
        placement="bottom"
        closable={false}
        open={open}
        height="200px"
        mask={false}
        headerStyle={{
          height: '35px',
          borderTop: '1px solid rgba(5,5,5,0.06)',
          backgroundColor: '#fff',
        }}
      >
        <div
          id="line"
          className="drawer_line"
          onMouseDown={(e) => onmousedown(e)}
        />
        {/* 你的代码 */}
      </Drawer>
    </div>
  );
}

export default Index;

resizableStyle.scss 文件如下 :

.drawer_line {
  position: absolute;
  left: 50%;
  top: 0;
  height: 8px;
  width: 30px;
  border-top: 1px solid rgba(5, 5, 5, 0.06);
  background: #ffffff;
}

.drawer_line:hover {
  cursor: ns-resize; // 北南方向
  position: absolute; 
  left: 50%;
  top: 0;
  height: 8px;
  width: 30px;
  background: #345df5;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值