react-draggable实现拖拽

安装react-draggable插件

npm install react-draggable

设置无限制的拖动范围

创建jsx文件

import React from "react";

// 引入样式

import './index.css'

// 引入拖拽插件

import Draggable from 'react-draggable';

export default function Tuo() {

  return (

    <div>

      <div className="app">

        <Draggable>

          <div className="box1">我可以随意移动box1</div>

        </Draggable>

        <Draggable>

          <div className="box2">我可以随意移动box2</div>

        </Draggable>

      </div>

    </div>

  );

}

引入css样式

.app {

  background-color: red;

  width: 800px;

  height: 500px;

  margin: auto;

  position: relative;

}

.box1 {

  background-color: rgb(127, 192, 127);

  width: 300px;

  height: 300px;

}

.box2 {

  background-color: rgb(142, 200, 107);

  width: 300px;

  height: 300px;

}

.box3 {

  background-color: rgb(112, 148, 194);

  width: 300px;

  height: 300px;

}

.box4 {

    background-color: rgb(174, 103, 160);

    width: 300px;

    height: 300px;

}

设置拖拽的范围

在父级内移动 

import React from "react";

// 引入样式

import "./index.css";

// 引入拖拽插件

import Draggable from "react-draggable";

export default function Tuo() {

  return (

    <div>

      <div className="app">

        {/* 限制范围*/}

        <Draggable bounds={{ right: 200, left: -400, top: 0, bottom: 200 }}>

          <div className="box3">我移动受限制box3</div>

        </Draggable>

      </div>

    </div>

  );

}

另一种在父级内移动 

import React from "react";

// 引入样式

import "./index.css";

// 引入拖拽插件

import Draggable from "react-draggable";

export default function Tuo() {

  return (

    <div>

      <div className="app">

        {/* 限制范围另一个方式*/}

        <Draggable bounds={".app"}>

          <div className="box4">我移动ye受限制box4</div>

        </Draggable>

      </div>

    </div>

  );

}

效果展示: 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值