拖拽功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .wsx{ width: 500px; height: 300px; background-color: red; position: absolute; left: 0px; top: 0px; } </style> </head> <body> <div class="wsx"></div> <script> // 1.获取元素 // 2.写入鼠标点击后移入移出 // 3.求出’点击‘的xy位置,求出盒子距离视口位置 // 4.求出鼠标移入时的x和y位置 - 点击时的xy位置 // 5.求出盒子距离视口距离 + 鼠标移入时的xy // 6.在样式的left和top赋值 // 7.if判断,如果超出或者小于当前视口则恢复默认 // 8.续上:获取整个屏幕宽度和盒子自身宽高 //获取元素 var wsx = document.querySelector('.wsx') //鼠标点击 wsx.onmousedown = function(e){ //求出点击的x,y位置 var x = e.clientX var y = e.clientY //求出盒子距离视口的距离,取出x和y var XY = wsx.getBoundingClientRect() var X1 = XY.left var Y1 = XY.top //获取整个视口宽高 var x4 = document.documentElement.clientWidth var y4 = document.documentElement.clientHeight //获取盒子自身宽高 var x5 = wsx.offsetWidth var y5 = wsx.offsetHeight //让视口整个宽高减去盒子自身宽高 var x6 = x4 - x5 var y6 = y4 - y5 //鼠标移入 wsx.onmousemove = function(e){ //求出鼠标移入时的x和y位置 - 点击时的xy位置 var x2 = e.clientX - x var y2 = e.clientY - y //求出盒子距离视口距离 + 鼠标移入时的xy var x3 = X1 + x2 var y3 = Y1 + y2 //判断x,y小于0,或者大于x,y if(x3 < 0){ x3 = 0 } if(x3 > x6){ x3 = x6 } if(y3 < 0){ y3 = 0 } if(y3 > y6){ y3 = y6 } //在样式的left和top赋值 wsx.style.left = x3 + 'px' wsx.style.top = y3 + 'px' } //鼠标移出 wsx.onmouseup = function(){ wsx.onmousemove = null } } </script> </body> </html>