学习笔记:鼠标拖拽优化

746 阅读1分钟
原文链接: www.divpc.cn

前言

之前在给一个元素添加拖拽的时候碰到如下问题: 在快速移动的时候,移动的元素没有跟随鼠标快速移动

原因

出现这个问题的原因是 mousemove 事件触发是有一个时间间隔的,比如每隔50ms(不一定是,只是假如)浏览器才会去获取一次鼠标当前的位置,触发mousemove事件并把当前鼠标信息传入回调函数中,所以当我们快速移动的时候在下一次检测之前, 我们的鼠标有可能已经移动出元素,这样就导致元素上绑定的鼠标事件不能正确执行.

解决办法

那怎么解决这个办法呢? 我们只需要把鼠标事件的mousedown事件绑定在元素上,然后把mousemove和mouseup事件绑定在document就可以了, 因为不管你如何快速移动,鼠标一直是在document上的

示例代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>无标题文档</title>
		<style>
			.block{
				position: absolute;
				width: 100px;
				height: 100px;
				background-color: red;
				cursor: move;
			}
		</style>
	</head>

	<body>
		<div class="block"></div>
	</body>
	<script type="text/javascript">
		var block = document.querySelector('.block');
		block.addEventListener('mousedown', moveStart);
		document.addEventListener('mousemove', moving);
		document.addEventListener('mouseup', moveEnd);
		
		var isDrap = false;
		var position = {
			x: 0,
			y: 0
		};
		var start = {
			x: 0,
			y: 0
		};
		function moveStart(e) {
			isDrap = true;
			start.x = e.pageX;
			start.y = e.pageY;
		}
		function moving(e) {
			if (!isDrap) return;
			let move = {
				x: e.pageX - start.x,
				y: e.pageY - start.y,
			}
			block.style.left = (position.x + move.x) + 'px';
			block.style.top = (position.y + move.y) + 'px';
		}
		function moveEnd(e) {
			isDrap = false;
			position = {
				x: block.offsetLeft,
				y: block.offsetTop
			}
		}
	</script>
	</body>
</html>