webAPI 鼠标拖拽demo

鼠标拖拽示例

简述

该示例为鼠标拖拽的简单实现案例

功能描述

  1. 鼠标在拖动区域按下时, 拖动盒子, 盒子跟随鼠标移动
  2. 鼠标松开时, 取消关联

代码

  • index.html
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>鼠标拖拽练习demo</title>
		<link rel="stylesheet" href="css/index.css" />
	</head>
	<body>
		<div id="box">
			<div id="box-hand">拖拽区域</div>
		</div>
	</body>
</html>
<script>
	// 鼠标按下时, 拖动盒子, 盒子跟随鼠标移动
	// 鼠标松开时, 取消关联
	// 关键点获取鼠标按下时, 鼠标在盒子中的位置, 在按下移动过程中鼠标相对盒子静止
	
	// 获取盒子元素
	const box = document.getElementById("box");
	// 获取盒子拖拽区域元素
	const drop = document.getElementById("box-hand");
	drop.onmousedown = function (e) {
		// 处理浏览器兼容问题
		e = e || window.event;
		// 鼠标按下时, 获取数据在盒子中的位置
		//  鼠标在盒子中的位置 = 鼠标在页面的位置 - 盒子在页面的位置
		console.log(box)
		const x = e.pageX - box.offsetLeft;
		const y = e.pageY - box.offsetTop;
		
		// 鼠标移动
		document.onmousemove = function (e) {
			// 处理浏览器兼容问题
			e = e || window.event;
			// 获取盒子的坐标
			// 盒子坐标 = 鼠标当前在页面的位置  - 鼠标在盒子中的位置
			const boxX = e.pageX - x;
			const boxY = e.pageY - y;
			
			// 重置盒子位置, 使盒子相对鼠标静止
			box.style.left = boxX + 'px';
			box.style.top = boxY + 'px';
		}
	}
	
	drop.onmouseup = function (e) {
		// 处理浏览器兼容问题
		e = e || window.event;
		// 鼠标松开时, 移除鼠标事件
		document.onmousemove = null;
	}

</script>

-index.css


#box{
	margin: auto;
	width: 400px;
	height: 300px;
	background-color: darkgray;
	position: absolute; // 需要改变盒子坐标必须脱离文档流
}

#box-hand {
	width: 100%;
	height: 35px;
	color: beige;
	line-height: 35px;
	background-color: cadetblue;
	cursor: move;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值