要实现页面元素的拖动,其原理就是根据鼠标的移动实时的更改元素的left 和 top值(当然元素肯定是要做绝对定位的)
function drag(box) {
	box.onmousedown = function() {// 鼠标按下事件
		!!box.setCapture && box.setCapture() //设置在鼠标按下时box捕获所有点击事件,setCapture在ie中生效
		let ol = event.clientX - box.offsetLeft // 求鼠标到box左边的距离
		let ot = event.clientY - box.offsetTop // 求鼠标到box顶部的距离
		document.onmousemove = function(event) {//鼠标移动
			event = event || window.event // 拿到鼠标事件
			let left = event.clientX - ol // 鼠标当前坐标 - 鼠标在box中的偏离量 = box的坐标
			let top = event.clientY - ot
			box.style.left = left + 'px' // 将鼠标坐标赋值给box的位置属性
			box.style.top = top + 'px'
			return false //取消拖拽后 浏览器的默认搜索事件
		}
		document.onmouseup = function() {//鼠标抬起事件
			document.onmousemove = null //取消onmousemove事件
			document.onmouseup = null //取消鼠标的onmouseup事件
			box.releaseCapture && box.releaseCapture() // 设置在鼠标抬起时box释放捕获的所有点击事件 releaseCapture在ie中生效
		}
	}
}说明:
鼠标抬起事件绑在document上,目的是为了防止box上面有元素遮罩,box的鼠标抬起事件失效
示例使用:
<style>
	#box {
		width: 100px;
		height: 100px;
		background-color: red;
		position: absolute;
	}
</style>
<div id="box">test</div>
<script>
	let box=document.getElementById('box');
	drag(box)
</script>本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!