日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

react實現拖拽功能

作者:筱闖~ 更新時間: 2023-07-14 編程語言
import React, { Component } from 'react';
import './index.css'
class DragBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
        left: 0,
        top: 0,
        isDragging: false,
        startX: 0,
        startY: 0
    };
  }

  handleMouseDown = (e) => {
    this.setState({
        isDragging: true,
        startX: e.clientX,
        startY: e.clientY
    });
  }

  handleMouseMove = (e) => {
    if (this.state.isDragging) {
        const offsetX = e.clientX - this.state.startX;
        const offsetY = e.clientY - this.state.startY;
        this.setState({
            left: this.state.left + offsetX,
            top: this.state.top + offsetY,
            startX: e.clientX,
            startY: e.clientY
        });
    }
  }

  handleMouseUp = (e) => {
    this.setState({
        isDragging: false
    });
  }

  render() {
    return (
        <div className="drag-box"
             style={{ left: this.state.left + 'px', top: this.state.top + 'px' ,position:'absolute'}}
             onMouseDown ={this.handleMouseDown} //鼠標按下事件
             onMouseMove={this.handleMouseMove} //鼠標移動事件
             onMouseUp={this.handleMouseUp} //鼠標抬起事件
             > 
            Drag me!
        </div>
    );
  }
}

export default DragBox;

onMouseDown //鼠標按下事件
onMouseMove //鼠標移動事件
onMouseUp //鼠標抬起事件

主要的實現思路是:鼠標移動到最后的左邊距和上邊距-鼠標按下的左邊距和上邊距然后給元素一個定位給它的left和top賦值就可實現

原文鏈接:https://blog.csdn.net/m0_64544033/article/details/130622286

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新