js拖拽盒子

示例在这里插入图片描述

完整代码


<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>拖拽盒子</title>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			.container {
				position: fixed;
				z-index: 1000;
				width: 100%;
				height: 100%;
				background: #00000073;
			}

			.box {
				width: 520px;
				height: 200px;
				background: #fff;
			}

			.box_drag {
				height: 60px;
				width: 100%;
				line-height: 60px;
				text-align: center;
				border-bottom: 1px dashed #ccc;
				user-select: none;
				color: #69c0ff;
				cursor: move;
			}
		</style>
	</head>
	<body>
		<div class="container">
			<div class="box">
				<div class="box_drag">鼠标移动上来拖动盒子</div>
			</div>
		</div>
		<script>
			(function dragDom() {
				let dragDomMove = document.querySelector('.box')
				let dragDom = document.querySelector('.box_drag')
				let drag = true
				let location = [0, 0]
				if (!drag) return
				// 事件按下
				dragDom.onmousedown = function(event) {
					dragDomMove.style.position = "absolute"
					let X, Y
					let maxPosition = [window.innerWidth, window.innerHeight] //最大滚动位置
					let boxSize = [dragDomMove.offsetWidth, dragDomMove.offsetHeight] //盒子宽高
					let curPosition = [event.clientX, event.clientY] // 获取当前的x、y轴距离
					let prePosition = getDragMoveAxis(dragDomMove.style.transform) // 获取鼠标在方块内的轴距
					let innerX = curPosition[0] - prePosition[0] // 获取鼠标在方块内的x轴距
					let innerY = curPosition[1] - prePosition[1] // 获取鼠标在方块内的y轴距
					// 事件拖动
					document.onmousemove = function(e) {
						// 边界限制
						X = e.clientX - event.offsetX < 0 ? 0 : maxPosition[0] - e.clientX > 0 ? e.clientX - innerX :
							X
						Y = e.clientY - event.offsetY < 0 ? 0 : maxPosition[1] - e.clientY > 0 ? e.clientY - innerY :
							Y
						if (maxPosition[0] - X > boxSize[0]) {
							location[0] = X
						} else {
							location[0] = maxPosition[0] - boxSize[0]
						}
						if (maxPosition[1] - Y > boxSize[1]) {
							location[1] = Y
						} else {
							location[1] = maxPosition[1] - boxSize[1]
						}
						dragDomMove.style.transform = `translate(${location[0]}px, ${location[1]}px)`
					}
					// 事件清除
					document.onmouseup = function() {
						document.onmousemove = null
						document.onmouseup = null
					}
				}
			})()
			function getDragMoveAxis(data) {
				var clientArr = data.match(/\d+(\.\d+)?/g) || [0, 0];
				//字符串数组转数字数组
				return clientArr.map(Number)
			}
		</script>
	</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值