鼠标事件,拖动元素块

<html>
	<head>
		<meta charset="utf-8" />
		<title>鼠标事件</title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}
			div {
				width: 200px;
				height: 200px;
				top: 0;
				left: 0;
				position: absolute;
				background: orange;
				cursor: pointer;
			}
		</style>
	</head>
	<body>
		<div></div>
	</body>
	<script>
		// 获取div对象
		var oDiv = document.getElementsByTagName('div')[0]
		// 计算元素移动的最大偏移位置
		var maxLeft = window.innerWidth - oDiv.offsetWidth
		var maxTop = window.innerHeight - oDiv.offsetHeight
		
		
		// 鼠标按下事件
		oDiv.onmousedown = function (e) {
			// 兼容获取事件
			var ev = e || event
			
			// 获取点击事件的位置
			// console.log(ev.clientX + 'x' + ev.clientY)
			
			// 记录鼠标按下的点的位置
			var posX = ev.clientX - oDiv.offsetLeft
			var posY = ev.clientY - oDiv.offsetTop
			
			// 鼠标移动事件(不要做耗时操作)
			document.onmousemove = function (e) {
				var ev = e || event
				
				// 获取鼠标移动位置
				// console.log(ev.clientX + 'x' + ev.clientY)
				
				// 计算鼠标移动点的位置
				var left = ev.clientX - posX
				var top = ev.clientY - posY
				
				// 边界判断
				if (left < 0) {
					left = 0
				} else if (left > maxLeft) {
					left = maxLeft
				} else if (top > maxTop) {
					top = maxTop
				}
				
				// 重新设置属性
				oDiv.style.left = left + 'px'
				oDiv.style.top = top + 'px'
			}
			// 鼠标抬起事件
			document.onmouseup = function () {
				document.onmousemove = null
				document.onmouseup = null
			}
		}
		
	</script>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_43789195/article/details/85080799
今日推荐