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

學無先后,達者為師

網站首頁 編程語言 正文

react實現(xiàn)簡單的拖拽功能_React

作者:至_臻 ? 更新時間: 2022-05-08 編程語言

本文實例為大家分享了react實現(xiàn)簡單的拖拽功能的具體代碼,供大家參考,具體內容如下

src文件夾下新建文件夾demo ?然后在創(chuàng)建兩個文件js和css

demo.js文件代碼

// react實現(xiàn)拖拽
import React from 'react'
// 引入css樣式
import './demo.css'
class Drag extends React.Component {
? ? constructor(props) {
? ? ? ? super(props);
? ? ? ? this.state = {
? ? ? ? ? ? translateX: 0,
? ? ? ? ? ? translateY: 0,
? ? ? ? };
? ? }
? ? small_down = (e) => {
? ? ? ? var obig = this.refs.move.parentNode;
? ? ? ? var osmall = this.refs.move;
? ? ? ? var e = e || window.event;
? ? ? ? /*用于保存小的div拖拽前的坐標*/
? ? ? ? osmall.startX = e.clientX - osmall.offsetLeft;
? ? ? ? osmall.startY = e.clientY - osmall.offsetTop;
? ? ? ? /*鼠標的移動事件*/
? ? ? ? document.onmousemove = function (e) {
? ? ? ? ? ? var e = e || window.event;
? ? ? ? ? ? osmall.style.left = e.clientX - osmall.startX + "px";
? ? ? ? ? ? osmall.style.top = e.clientY - osmall.startY + "px";
? ? ? ? ? ? /*對于大的DIV四個邊界的判斷*/
? ? ? ? ? ? let x = obig.offsetWidth - osmall.offsetWidth
? ? ? ? ? ? let y = obig.offsetHeight - osmall.offsetHeight
? ? ? ? ? ? if (e.clientX - osmall.startX <= 0) {
? ? ? ? ? ? ? ? osmall.style.left = 0 + "px";
? ? ? ? ? ? }
? ? ? ? ? ? if (e.clientY - osmall.startY <= 0) {
? ? ? ? ? ? ? ? osmall.style.top = 0 + "px";
? ? ? ? ? ? }
? ? ? ? ? ? if (e.clientX - osmall.startX >= x) {
? ? ? ? ? ? ? ? osmall.style.left = x + "px";
? ? ? ? ? ? }
? ? ? ? ? ? if (e.clientY - osmall.startY >= y) {
? ? ? ? ? ? ? ? osmall.style.top = y + "px";
? ? ? ? ? ? }
? ? ? ? };
? ? ? ? /*鼠標的抬起事件,終止拖動*/
? ? ? ? document.onmouseup = function () {
? ? ? ? ? ? document.onmousemove = null;
? ? ? ? ? ? document.onmouseup = null;
? ? ? ? };
? ? }
? ? componentDidMount() {
? ? }
? ? render() {
? ? ? ? return (
? ? ? ? ? ? 
? ? ? ? ? ? ? ?
this.small_down(e)} style={{ position: "absolute", left: `${this.state.translateX}px`, top: `${this.state.translateY}px` }} /> ? ? ? ? ? ?
? ? ? ? ) ? ? } }; export default Drag

demo.css代碼

.box{
? width: 100vw;
? height: 100vh;
? position: relative;
}
?
.box-item{
? position: absolute;
? width: 100px;
? height: 100px;
? background: pink;
}

App.js里面

import './App.css';
// 引入demo這個文件
import Drag from './demo/demo'
import React from 'react';
?
class App extends React.Component {
? constructor(props) {
? ? super(props)
? }
? render() {
? ? return (
? ? ? 
? ? ? ? ? ? ?
? ? ? ) ? } } export default App;

這樣就可以實現(xiàn)一個簡單的拖拽了

原文鏈接:https://blog.csdn.net/weixin_57163112/article/details/119856192

欄目分類
最近更新