html标签拖动组件封装(react)
直接上组件(可以直接使用)
import React from 'react';
import scss from "../../../assets/styles/map.module.scss";
/**
*
* @param el
* @param event
* @param handler
* @returns
*
* 添加拖动事件
*/
const addEvent = (el: any, event: any, handler: any) => {
if (!el) return;
if (el.attachEvent) {
el.attachEvent('on' + event, handler);
} else if (el.addEventListener) {
el.addEventListener(event, handler, false);
} else {
el['on' + event] = handler;
}
};
/**
*
* @param el
* @param event
* @param handler
* @returns
* 移除拖动事件
*/
const removeEvent = (el: any, event: any, handler: any) => {
if (!el) return;
if (el.detachEvent) {
el.detachEvent('on' + event, handler);
} else if (el.removeEventListener) {
el.removeEventListener(event, handler, false);
} else {
el['on' + event] = null;
}
};
interface State {
needX: number;
needY: number;
}
interface Props {
style: any
}
/*拖拽组件*/
class Drag extends React.Component<Props, State> {
disX: any;
disY: any;
constructor(props: any) {
super(props);
this.state = {
/*定义两个值用来存放当前元素的left和top值*/
needX: 90,
needY: 150,
}
/*定义两个值用来存放鼠标按下的地方距离元素上侧和左侧边界的值*/
this.disX = 0;
this.disY = 0;
}
/*定义鼠标下落事件*/
fnDown = (e: any) => {
/*事件兼容*/
const event = e || window.event;
/*获取鼠标按下的地方距离元素左侧和上侧的距离*/
this.disX = event.clientX - this.state.needX;
this.disY = event.clientY - this.state.needY;
// /*定义鼠标移动事件*/
addEvent(document, 'mousemove', this.fnMove);
// /*定义鼠标抬起事件*/
addEvent(document, 'mouseup', this.fnUp);
}
/*定义鼠标移动事件*/
fnMove = (e: any) => {
/*事件兼容*/
const event = e || window.event;
this.setState({
needX: event.clientX - this.disX,
needY: event.clientY - this.disY,
});
}
fnUp = () => {
removeEvent(document, 'mousemove', this.fnMove);
removeEvent(document, 'mouseup', this.fnUp);
}
render() {
/*返回元素*/
return (
<div
style={{
width: this.props.style.width,
height: this.props.style.height,
position: this.props.style.position,
left: this.state.needX,
top: this.state.needY
}}
>
<div
onMouseDown={this.fnDown}
className={scss['drag-btn']}
>
<span className={scss['btn-span']}></span>
</div>
{this.props.children}
</div>
)
}
}
export default Drag
注释:转发请注明出处.