鼠标拖拽div移动

本文介绍如何使用JavaScript和HTML5实现div元素的鼠标拖拽移动功能,包括详细步骤和代码示例。

鼠标拖拽div移动

效果图:
在这里插入图片描述

代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>鼠标拖拽div移动</title>
		<style>
			*{
				margin: 0;
				padding: 0;
			}
			#box{
				width: 100px;
				height: 100px;
				position: relative;
				background-color: #FF0000;
			}
		</style>
		<script type="text/javascript">
			window.onload = function(){
				let boxx = 0;
				let boxy = 0;
				var isDown = false;
				//用于存储新的光标坐标
				let mosx = 0;
				let mosy = 0;
				let mosx2 = 0;
				let mosy2 = 0;
				
				//获取box
				const box = document.getElementById('box');
				//box元素鼠标按下触发事件
				box.onmousedown  = function(e){
					
					//获取并记录鼠标第一次按下时光标的坐标
					mosx = e.pageX;
					mosy = e.pageY;
					
					//开关打开
					isDown = true;
				};
				
				//设置鼠标移动事件
				window.onmousemove = function(e){
					if (!isDown) {
					    return;
					}
					//获取光标移动时光标的新坐标
					mosx2 = e.pageX;
					mosy2 = e.pageY;
					//计算box的新坐标
					boxx += (mosx2 - mosx);
					boxy += (mosy2 - mosy);
					//将光标的旧坐标更新
					mosx = mosx2;
					mosy = mosy2;
					//移动box
					box.style.top = boxy + "px";
					box.style.left = boxx + "px";
				};
				
				//鼠标放开触发事件
				box.onmouseup  = function(){
					isDown = false;
				};
			};
		</script>
	</head>
	<body>
		<div id="box"></div>
	</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值