0
点赞
收藏
分享

微信扫一扫

鼠标拖动元素位置

夏侯居坤叶叔尘 2022-01-10 阅读 34
javascript

鼠标拖动元素位置

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body >
		<div id="box" style="width: 100px; height: 100px; background-color: aqua; position: absolute;">

		</div>
		<script>
			function moveBox(e) {
				var windowWidth = window.innerWidth;
				var windowHeight = window.innerHeight;
				var x = e.clientX;
				var y = e.clientY;

				if (x - divBoxWidth / 2 < 0) {
					x = 0;
				} else if (x + divBoxWidth / 2 > windowWidth) {
					x = windowWidth - divBoxWidth;
				} else {
					x -= divBoxWidth / 2
				}

				if (y - divBoxHeight / 2 < 0) {
					y = 0;
				} else if (y + divBoxHeight / 2 > windowHeight) {
					y = windowHeight - divBoxHeight;
				} else {
					y -= divBoxHeight / 2
				}

				divBox.style.top = y + 'px';
				divBox.style.left = x + 'px';
			}
			var divBox = document.getElementById('box');
			var divBoxWidth = divBox.clientWidth;
			var divBoxHeight = divBox.clientHeight;
			divBox.addEventListener('mousedown', function() {
				document.addEventListener('mousemove', moveBox)
			})

			divBox.addEventListener('mouseup', function() {
				document.removeEventListener('mousemove', moveBox)
			})
		</script>
	</body>
</html>

举报

相关推荐

0 条评论