欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

原生js的拖拽事件

程序员文章站 2022-06-30 19:13:36
...
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.box{
			width:200px;
			height:200px;
			background-color: red;
			position: absolute;
			left:0;
			top:0;
		}
	</style>
</head>
<body>
	<div class='box'></div>
	<script>
		var box = document.querySelector('.box');
		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(event){
				// 注意:这里要有自己的事件对象
				target.style.left = event.clientX - disX + 'px';
				target.style.top = event.clientY - disY + 'px';
				document.onmouseup = function(){
					document.onmousedown = null;
					document.onmousemove = null;
				}
			}
		}
	</script>
	
</body>
</html>

 

相关标签: 拖拽