react按钮拖拽_react 拖拽

本文介绍了一个React组件中实现拖拽功能的方法。通过监听触摸事件,实现了元素在限定范围内的自由拖动,并结合定时器判断是否触发点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近做一个功能,一个点击按钮,需要支持拖拽。完成后谢在这里做一下笔记。

export default class Record extends Component {

constructor(props) {

super(props);

// 限制最大宽高,不让滑块出去

this.dragLimit = {

maxW: null,

maxH: null,

};

this.timer = null;

}

// 认购记录拖拽

recordDrag = (e) => {

if (this.timer) {

clearTimeout(this.timer);

this.timer = null;

}

this.timer = setTimeout(() => {

// 执行点击事件

window.location.hash = `#${Routers.Record}`;

}, 500);

const ev = e || window.event;

const touch = ev.targetTouches[0];

const bragBox = document.querySelector('#apply-record');

const containerBox = document.querySelector('#cal-wrap');

if (!bragBox || !containerBox) {

return;

}

if (this.dragLimit.maxW === null || this.dragLimit.maxH === null) {

this.dragLimit = {

maxW: containerBox.clientWidth - bragBox.offsetWidth,

maxH: containerBox.clientHeight - bragBox.offsetHeight,

};

}

// 手指触摸开始,记录盒子的初始位置

const oL = touch.clientX - bragBox.offsetLeft;

const oT = touch.clientY - bragBox.offsetTop;

// 触摸中的,位置记录

bragBox.addEventListener('touchmove', (e1) => {

if (this.timer) {

clearTimeout(this.timer);

this.timer = null;

}

const ev1 = e1 || window.event;

const touch1 = ev1.targetTouches[0];

let oLeft = touch1.clientX - oL;

let oTop = touch1.clientY - oT;

if (oLeft < 0) {

oLeft = 0;

} else if (oLeft >= this.dragLimit.maxW) {

oLeft = this.dragLimit.maxW;

}

if (oTop < 0) {

oTop = 0;

} else if (oTop >= this.dragLimit.maxH) {

oTop = this.dragLimit.maxH;

}

bragBox.style.left = `${oLeft}px`;

bragBox.style.top = `${oTop}px`;

});

// 触摸结束时的处理

bragBox.addEventListener('touchend', () => {

document.removeEventListener('touchmove', (evt) => {

// 阻止默认事件

evt.preventDefault();

});

});

}

render() {

return (

...

{/* 认购记录 */}

...

);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值