原生JS实现拖拽

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>原生JS--drag</title>
	<style>
		*{
			margin:0;
			padding:0;
		}
		#drag{
			width:100px;
			height:100px;
			background-color: red;
			position: absolute;
		}
	</style>
</head>
<body>
	<div id='drag' style='left:0;top:0'></div>
	<script>
		var box = document.getElementById('drag');
		box.onmousedown = function(e){
			// 事件对象兼容
			var event = e || window.event;
			//事件源兼容
			var target = event.target || event.srcElement;
			//获取鼠标按下的地方距离元素左侧和上侧的距离
			var disX = event.clientX - target.offsetLeft;
			var disY = event.clientY - target.offsetTop;
			//定义鼠标移动事件
			document.onmousemove = function(e){
				// 事件对象兼容
				var event = e || window.event;
				// 事件源兼容(注意:凑出不能修改事件源,否则会出现若鼠标移出div则target变为HTML)
				// var target = event.target || event.srcElement;
				//移动
				target.style.left = event.clientX - disX + 'px';
				target.style.top = event.clientY - disY + 'px';
			}
			document.onmouseup = function(){
				//鼠标抬起时解除事件绑定
				document.onmousemove = null;
				document.onmouseup = null;
			}
		}
	</script>
</body>
</html>

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页