<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> </head> <style type="text/css"> *{ margin: 0; padding: 0; } div{ width: 500px; height: 500px; background-color: yellow; position: absolute; } </style> <body> <div> box </div> <script type="text/javascript"> var box = document.getElementsByTagName("div")[0]; var mouseOffsetX = 0; //偏移 var mouseOffsetY = 0; var isDraging = false; //是否可拖拽标记 //鼠标事件1 在盒子按下(要计算鼠标相对拖拽元素左上角的坐标,并且标记元素为可拖拽) box.addEventListener('mousedown', function(e){ var e = e || window.event; mouseOffsetX = e.pageX-box.offsetLeft; mouseOffsetY = e.pageY-box.offsetTop; console.log(mouseOffsetX); console.log(mouseOffsetY); isDraging = true; }) // 事件2 鼠标移动时、检测元素是否可标记为移动,如果是则更新位置 document.onmousemove = function(e){ var e = e || window.event; var mouseX = e.pageX; //鼠标当前位置 var mouseY = e.pageY; var moveX = 0; var moveY = 0; if(isDraging === true){ moveX = mouseX - mouseOffsetX; moveY = mouseY - mouseOffsetY; //范围限定 moveX > 0 并且 moveX < (页面最大宽度 - 浮层的宽度) // moveY > 0 并且 moveY < (页面最大高度 - 浮层的高度) var pageWidth = document.documentElement.clientWidth; var pageHeight = document.documentElement.clientHeight; // 盒子宽度、高度 var boxWidth = box.offsetWidth; var boxHeight = box.offsetHeight; // 页面最大宽度、高度 var maxX = pageWidth - boxWidth; var maxY = pageHeight - boxHeight; // 盒子移动距离 moveX = Math.min( maxX , Math.max( 0 , moveX)); moveY = Math.min( maxY , Math.max( 0 , moveY)); box.style.left = moveX + 'px'; box.style.top = moveY + 'px'; } } // 鼠标事件3 鼠标松开的时候(标记元素为不可拖拽) document.onmouseup = function(){ isDraging = false; } </script> </body> </html>
网友评论