1. 程式人生 > >react 拖拽元件(PC端)

react 拖拽元件(PC端)

簡單封裝了下

import React from 'react'

const addEvent = (el, event, handler) => {
	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;
	}
  };
  
const removeEvent = (el, event, handler) => {
	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;
	}
};

/*拖拽元件*/
class Drag extends React.Component {
	constructor() {
		super();
		this.state = {
			/*定義兩個值用來存放當前元素的left和top值*/
			needX: 0,
			needY: 0,
		}
		/*定義兩個值用來存放滑鼠按下的地方距離元素上側和左側邊界的值*/
		this.disX = 0;
		this.disY = 0;
	}
	/*定義滑鼠下落事件*/
	fnDown = (e) => {
		/*事件相容*/
		const event = e || window.event;
		/*事件源物件相容*/
		const target = event.target || event.srcElement;
		/*獲取滑鼠按下的地方距離元素左側和上側的距離*/
		this.disX = event.clientX - target.offsetLeft;
		this.disY = event.clientY - target.offsetTop;
		// /*定義滑鼠移動事件*/
		addEvent(document, 'mousemove', this.fnMove);
		// /*定義滑鼠擡起事件*/
		addEvent(document, 'mouseup', this.fnUp);
	}
	/*定義滑鼠移動事件*/
	fnMove = (e) => {
		/*事件相容*/
		const event = e || window.event;
		/*事件源物件相容*/
		const target = event.target || event.srcElement;
		this.setState({
			needX: event.clientX - this.disX,
			needY: event.clientY - this.disY,
		});
		this.props.onMove({offsetX: this.state.needX, offsetY: this.state.needY});
	}
	fnUp = () => {
		removeEvent(document, 'mousemove', this.fnMove);
    	removeEvent(document, 'mouseup', this.fnUp);
	}
	render() {
		/*返回元素*/
		return (
			<div onMouseDown={this.fnDown} style={{
				width: this.props.style.width,
				height: this.props.style.height,
				backgroundColor: this.props.style.backgroundColor,
				position: this.props.style.position,
				left: this.state.needX,
				top: this.state.needY,
				// transform: `translate(${this.state.needX}px, ${this.state.needY}px)`,
				cursor: "pointer",
			}}
			>{this.props.children}</div>
		)
	}
}
export default Drag

使用的話引用下就行

<Drag style={{width:'100px',height:'100px',backgroundColor:'green',position:'absolute'}} onMove={(offet)=>{
	console.log("拖拽元素當前位置:",offet);
}}>
	<div style={{
		pointerEvents: "none",
        width:'50px',
		height:'50px',
		background: "url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1539180607654&di=6435dc00382b5d7682646cae1c36ca1b&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F9358d109b3de9c82036507ac6681800a19d84395.jpg) center center / 100% no-repeat",
		backgroundSize: "100% 100%",
	}}>sdsfds</div>
</Drag>

在父元件繫結onMove即可打印出實時的座標