js基础之拖拽

js基础之拖拽
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
            * {
                padding: 0;
                margin: 0;
            }
			.container {
                width: 200px;
                height: 200px;
                background: red;
                position: absolute;
            }
		</style>
	</head>
	<body>
		<div class="container"></div>
		<script>
			var div = document.querySelector("div")
            const width = document.documentElement.clientWidth || document.body.clientWidth
            const height = document.documentElement.clientHeight || document.body.clientHeight
			var maxLeft = width - div.offsetWidth,
				maxTop = height - div.offsetHeight
			div.onmousedown = (e) => {
				e = e || window.event
				// 获取鼠标距离div边缘
				var disX = e.offsetX,
					disY = e.offsetY
				document.onmousemove = (e) => {
					e = e || window.event
					//鼠标距离屏幕边缘-鼠标距离div边缘
					var _left = e.clientX - disX,
						_top = e.clientY - disY
					// 判断不能超出屏幕边界
					if(_left < 0) _left = 0
					if(_top < 0) _top = 0
					if(_left > maxLeft) _left = maxLeft
					if(_top > maxTop) _top = maxTop
					
					div.style.left = _left + "px"
					div.style.top = _top + "px"
				}
				// 鼠标抬起,解绑move事件
				document.onmouseup = () => {
					document.onmousemove = null
				}
				return false
			}
		</script>
	</body>
</html>

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值