实例
注意几个知识点:
1、offsetLeft获取元素到页面左边的位置,this.style.left:当前元素到页面左边的位置;
2、event.clientX鼠标坐标
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div{ width:100px;height:100px;border-radius:50%; background-color:lightcoral; box-shadow:2px 2px 1px lightslategray; position:absolute; } </style> </head> <body> <div id="ball"> </div> <script> //onmousedown onmousemove onmouseup //小球移动:根据小球在文档中的坐标,不断变化X,Y轴的值实现 //小球到文档大小表示方式:this.style.left、this.style.top //this.style.left 与 offsetleft区别关系;this.style.left有单位是px,offsetleft是获取位置不带单位。 var ball = document.querySelector('div'); ball.onmousedown = function(event){ var x = event.clientX -this.offsetLeft; //鼠标在文档中X坐标减掉ball X边缘到文档的值=鼠标X坐标到ball边缘的值(不变) var y = event.clientY -this.offsetTop; //Y,同理上; document.onmousemove = function(event){ ball.style.left = event.clientX - x + 'px'; ball.style.top = event.clientY - y + 'px'; } document.onmouseup = function(){ this.onmousemove = null ; } } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例