1. 程式人生 > >react---拖拽元件

react---拖拽元件

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>drag--react</title>
	<script src='react.js'></script>
	<script src='react-dom.js'></script>
	<script src='babel.min.js'></script>
</head>
<style>
	*{
		margin:0;
		padding:0;
	}
</style>
<body>
	<div id='example'></div>
	<script type='text/babel'>
		/*拖拽元件*/
		class Drag extends React.Component{
			constructor(){
				super();
				this.state = {
					/*定義兩個值用來存放當前元素的left和top值*/
					needX:0,
					needY:0
				}
				/*定義兩個值用來存放滑鼠按下的地方距離元素上側和左側邊界的值*/
				this.disX = 0;
				this.disY = 0;
			}
			/*定義滑鼠下落事件*/
			fnDown(e){
				/*事件相容*/
				let event = e || window.event;
				/*事件源物件相容*/
				let target = event.target || event.srcElement;
				/*獲取滑鼠按下的地方距離元素左側和上側的距離*/
				this.disX = event.clientX - target.offsetLeft;
				this.disY = event.clientY - target.offsetTop;
				/*定義滑鼠移動事件*/
				document.onmousemove = this.fnMove.bind(this);
				/*定義滑鼠擡起事件*/
				document.onmouseup = this.fnUp.bind(this);
			}
			/*定義滑鼠移動事件*/
			fnMove(e){
				/*事件相容*/
				let event = e|| window.event ;
				/*事件源物件相容*/
				let target = event.target || event.srcElement;
				this.setState({
					needX:event.clientX - this.disX,
					needY:event.clientY - this.disY
				});
			}
			fnUp(){
				document.onmousemove = null;
				document.onmuseup = null;
			}
			render(){
				/*返回元素*/
				return (
					<div 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}} onMouseDown={this.fnDown.bind(this)}></div>
				)
			}
		}
		ReactDOM.render(
			/*渲染元件*/
			/*通過props屬性進行傳值*/
			<Drag style={{width:'100px',height:'100px',backgroundColor:'green',position:'absolute'}}/>,
			document.getElementById('example')
		);
	</script>
</body>
</html>