react中实现可拖动div

更新日期: 2020-02-24 阅读: 3.9k 标签: react

把拖动div功能用react封装成class,在页面直接引入该class即可使用。

title为可拖动区域。panel为要实现拖动的容器。

优化了拖动框超出页面范围的情况,也优化了拖动太快时鼠标超出可拖动区域的情况,优化了拖动会卡顿的情况。

 

页面中添加引入方法:

<Draggable panelId="要拖动容器的id" titleId="容器内标题的id" contentId="容器内除标题外的其他部分id" setPanelPosition={this.setPanelPosition.bind(this)}/>

页面中添加拖拽回调函数

  //推拽回调函数
  setPanelPosition(left,top){
    this.setState({pageX: left, pageY: top})
  }

要拖动的div如下:

<div id="要拖动的id" style={{left:this.state.pageX,top:this.state.pageY}}></div>

 

封装的class代码

import React from 'react';
class Draggable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }
  //拖拽
  initDrag(){
    let {panelId,titleId,contentId} = this.props;
    this.paneldom = document.getElementById(panelId);
    this.titleDom = document.getElementById(titleId);
    this.contentDom = document.getElementById(contentId);
    this.backgroundDom = document.body;
    this.bindEvent();
  }

  //region event
  componentDidMount() {
    this.initDrag();
  }
  bindEvent(){
    this.titleDom.onmousedown = this.onMouseDown.bind(this);
    this.titleDom.onmouseup = this.onMouseUp.bind(this);
    this.titleDom.onmousemove = this.onMouseMove.bind(this);

    this.contentDom.onmouseup = this.onContentMouseUp.bind(this);
    this.contentDom.onmousemove = this.onContentMouseMove.bind(this);

    this.backgroundDom.onmouseup = this.onBackgroundMouseUp.bind(this);
    this.backgroundDom.onmousemove = this.onBackgroundMouseMove.bind(this);
    let step = ()=>{
      this.activeAnimation = true;
      window.requestAnimationFrame(step);
    };
    window.requestAnimationFrame(step);
  }

  /**
   * 鼠标按下,设置modal状态为可移动,并注册鼠标移动事件
   * 计算鼠标按下时,指针所在位置与modal位置以及两者的差值
   **/
  onMouseDown (e) {
    const position = this.getPosition(e)
    this.setState({moving: true, diffX: position.diffX, diffY: position.diffY})
  }

  // 松开鼠标,设置modal状态为不可移动
  onMouseUp (e) {
    const { moving } = this.state
    moving && this.setState({moving: false});
  }

  // 鼠标移动重新设置modal的位置
  onMouseMove (e) {
    const {moving, diffX, diffY} = this.state
    if (moving) {
      if(this.activeAnimation){
        // 获取鼠标位置数据
        const position = this.getPosition(e)
        // 计算modal应该随鼠标移动到的坐标
        const x = position.mouseX - diffX
        const y = position.mouseY - diffY
        // 窗口大小,结构限制,需要做调整,减去侧边栏宽度
        const { clientWidth, clientHeight } = document.documentElement
        const modal = this.panelDom
        if (modal) {
          // 计算modal坐标的最大值
          const maxHeight = clientHeight - modal.offsetHeight
          const maxWidth = clientWidth - modal.offsetWidth
          // 判断得出modal的最终位置,不得超出浏览器可见窗口
          const left = x > 0 ? (x < maxWidth ? x : maxWidth) : 0
          const top = y > 0 ? (y < maxHeight ? y : maxHeight) : 0
          if(this.props.setPanelPosition){
            this.props.setPanelPosition(left,top);
          }
        }
        this.activeAnimation = false;
      }
    }
  }
  onContentMouseMove(e){
    let obj = {};
    obj.target = this.titleDom;
    obj.pageX = e.pageX;
    obj.screenY = e.screenY;
    this.onMouseMove(obj);
  }
  onContentMouseUp(){
    this.onMouseUp();
  }
  onBackgroundMouseMove(e){
    let obj = {};
    obj.target = this.titleDom;
    obj.pageX = e.pageX;
    obj.screenY = e.screenY;
    this.onMouseMove(obj);
  }
  onBackgroundMouseUp(){
    this.onMouseUp();
  }
  //endregion

  //region request
  // 获取鼠标点击title时的坐标、title的坐标以及两者的位移
  getPosition (e) {
    // 标题DOM元素titleDom
    const titleDom = e.target
    // titleDom的坐标(视窗)
    const X = titleDom.getBoundingClientRect().left
    // 由于Y轴出现滚动条,需要与鼠标保持一致,存储页面相对位置
    const Y = this.panelDom.offsetTop

    // 鼠标点击的坐标(页面)
    let mouseX = e.pageX
    let mouseY = e.screenY
    // 鼠标点击位置与modal的位移
    const diffX = mouseX - X
    const diffY = mouseY - Y
    return {X, Y, mouseX, mouseY, diffX, diffY}
  }
  //endregion

  //region render
  //endregion

  //region clear
  //endregion

  render() {
    return (
      <>
      </>
    );
  }
}
export default Draggable;

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://fly63.com/article/detial/8754

相关推荐

Gatsby.js_一款基于React.js静态站点生成工具

Gatsby能快速的使用 React 生态系统来生成静态网站,可以结合React Component、Markdown 和服务端渲染来完成静态网站生成让他更强大。

解决vscode 开发react 导入绝对路径 无法跳转的问题

相对路径可正常跳转,但是在webpack配置alias使用绝对路径后无法跳转.解决办法:需要添加一个jsconfig文件,如下:

react router中页面传值的三种方法

这篇文章主要介绍React Router定义路由之后如何传值,有关React和React Router 。react router中页面传值的三种方法:props.params、query、state

React常用hook的优化useEffect浅比较

先说说react原版的useEffect使用起来不便的地方,这里的effect每次更新都会执行,因为第三个参数一直是不等的,第二是在deps依赖很多的时候是真的麻烦

React 监听页面滚动,界面动态显示

当页面滚动时,如何动态切换布局/样式, 添加滚动事件的监听/注销

React + Webpack 构建打包优化

React 相关的优化:使用 babel-react-optimize 对 React 代码进行优化,检查没有使用的库,去除 import 引用,按需打包所用的类库,比如 lodash 、echarts 等.Webpack 构建打包存在的问题两个方面:构建速度慢,打包后的文件体积过大

react-router v4 按需加载的配置方法

在react项目开发中,当访问默认页面时会一次性请求所有的js资源,这会大大影响页面的加载速度和用户体验。所以添加按需加载功能是必要的,以下是配置按需加载的方法

React事件处理函数必须使用bind(this)的原因

学习React的过程中发现调用函数的时候必须使用bind(this),之后直接在class中声明函数即可正常使用,但是为什么呢,博主进行了一番查阅,总结如下。

grpc-web与react的集成

使用create-react-app脚手架生成react相关部分,脚手架内部会通过node自动起一个客户端,然后和普通的ajax请求一样,和远端服务器进行通信,只不过这里采用支持rpc通信的grpc-web来发起请求,远端采用docker容器的node服务器,node服务器端使用envoy作为代理

react中的refs属性的使用方法

React 支持一种非常特殊的属性 Ref ,你可以用来绑定到 render() 输出的任何组件上。这个特殊的属性允许你引用 render() 返回的相应的支撑实例( backing instance )。这样就可以确保在任何时间总是拿到正确的实例

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!