js实现拖拽案例

本文介绍了一个JavaScript实现的拖拽案例,展示了如何创建基本的拖放效果。通过示例代码,读者可以理解并应用到自己的项目中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

拽案例,效果如下:


代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title></title>
	<style>
		.box {
			width: 100px;
			height: 100px;
			background-color: red;
			position: absolute;
			left: 500px;
			top: 200px;
			cursor: pointer;
		}
	</style>
</head>
<script>
	window.onload = function () {
		//获取事件相关元素;
		var box = document.getElementsByClassName("box")[0];
		//给元素绑定onmousedown事件
		box.onmousedown = function (event) {
			//获取鼠标指针相对于盒子的距离;
			var x = event.clientX - box.offsetLeft;
			var y = event.clientY - box.offsetTop;

			//给盒子绑定onmousemove事件;
			document.onmousemove = function (event) {
				//盒子的位置等于鼠标指针的位置减去鼠标指针相对于盒子的位置;
				var xx = event.clientX - x;
				var yy = event.clientY - y;

				//将得到的xx和yy,两个距离加上px,赋值给box.style.left和box.style.top;
				box.style.left = xx + "px";
				box.style.top = yy + "px";
			}
		}

		//鼠标松开后,box不能继续跟着鼠标指针移动,所以给box绑定onmouseup事件,
		box.onmouseup = function () {
			//并给整个文档绑定鼠标移动事件为无效;
			document.onmousemove = null;
		}
	}
</script>
<body>
	<div class="box"></div>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值