听话的盒子

一、 实验想法

当我的鼠标按下去之后他就跟着鼠标移动,当我鼠标抬起时他就停止运动

二、实验思路

  1. 创建一个好看的移动物体(这里是一个方块代替)
  2. 知道鼠标点下去的坐标(作用在方块上的坐标)
  3. 获取方块的相对位置
  4. 获取方块的宽高
  5. 鼠标点下去时始终让鼠标在方块的中心位置(这里不然获取的一直是方块左上方的坐标)

三、实验步骤

当鼠标按下去时打印鼠标的相对位置
	<style>
			div{
				width: 100px;
				height: 100px;
				background-color: peru;
			}
		</style>
	</head>
	<body>
		<div></div>
		<script>
			let div = document.querySelector("div")
			
			div.onmousedown = function(event){      //鼠标按下起
				
				div.onmousemove = function(ev){     //鼠标移动时
					console.log(ev.offsetX)
					console.log(ev.offsetY)
				}
			}

		</script>
	</body>
</html>

鼠标位置的打印

结束鼠标的位置,不然一直跟着鼠标跑
div.onmouseup = function() {   //鼠标抬起时停止移动
				div.onmousemove = null
			}
 让盒子知道鼠标的位置
div.style.position = "absolute"//相对鼠标时盒子需要绝对定位(鼠标在哪盒子在哪)
			w = parseInt(getComputedStyle(div).width)		//获取盒子的宽
			h = parseInt(getComputedStyle(div).height)		//获取盒子的高

                 div.style.left = (ev.pageX - w / 2 ) + "px"  //鼠标的位置
			     div.style.top = (ev.pageY - h / 2 ) + "px"

成品代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			*{
				margin: 0;
				padding: 0;
			}
			div {
				width: 100px;
				height: 100px;
				background-color: peru;
			}
		</style>
	</head>
	<body>
		<div></div>
		<script>
			let div = document.querySelector("div")
			div.style.position = "absolute"				//相对鼠标时绝对定位(鼠标在哪盒子在哪)
			w = parseInt(getComputedStyle(div).width)		//获取盒子的宽
			h = parseInt(getComputedStyle(div).height)		//获取盒子的高
			div.onmousedown = function(event) { //鼠标按下起

				div.onmousemove = function(ev) { //鼠标移动时
					console.log(ev.offsetX)
					console.log(ev.offsetY)
					
					div.style.left = (ev.pageX - w / 2 ) + "px"  //鼠标的位置
					div.style.top = (ev.pageY - h / 2 ) + "px"
					
				}
			}
			
			div.onmouseup = function() {   //鼠标抬起时停止移动
				div.onmousemove = null
			}
		</script>
	</body>
</html>

四、效果展示

初始位置

被点击之后跟随鼠标移动的位置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

duoba_an

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值