e.offsetX是鼠标距离准确事件源的左上角距离
e.clientX是鼠标距离浏览器可视窗口左上角的距离
e.pageX是鼠标距离文档左上角的距离
/*
当鼠标点击div时开始挪动,当鼠标抬起,div静止——事件源是div当鼠标点击后,鼠标在移动——事件源是document
事件类型——鼠标事件
事件处理函数——要做的式是改变div的位置
*/<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>* {margin: 0;padding: 0;}div {width: 200px;height: 200px;background-color: pink;position: absolute;left: 0;top: 0;}</style> </head><body><div></div><script>var box = document.querySelector('div')var startX=0 //记录鼠标初始距离div的X位置var startY=0var flag = false //当点击div时移动div位置,否则不移动box.onmousedown = function (e) {startX = e.offsetXstartY = e.offsetYflag = true}document.addEventListener('mousemove', function (e) {if (flag == false) {return }x = e.clientX - startX;y = e.clientY - startY;if (x <= 0) {x = 0;}if (y <= 0) {y = 0;}box.style.left = x + "px";box.style.top = y + "px";})box.onmouseup = function (e) {flag = false //当抬起鼠标不移动// console.log('鼠标抬起的位置', e.offsetX, e.offsetY)}</script> </body></html>
优化:
x最大值应该是: