<!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> body { height: 3000px; } </style> </head> <body> <script> // 鼠标事件对象 MouseEvent document.addEventListener('click', function(e) { // 1. client 鼠标在可视区的x和y坐标 console.log(e.clientX); console.log(e.clientY); console.log('---------------------'); // 2. page 鼠标在页面文档的x和y坐标 console.log(e.pageX); console.log(e.pageY); console.log('---------------------'); // 3. screen 鼠标在电脑屏幕的x和y坐标 console.log(e.screenX); console.log(e.screenY); }) </script> </body> </html>
鼠标天使案例
<!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> img { position: absolute; top: 2px; } </style> </head> <body> <img src="images/angel.gif" alt=""> <script> var pic = document.querySelector('img'); document.addEventListener('mousemove', function(e) { // 1. mousemove只要我们鼠标移动1px 就会触发这个事件 // console.log(1); // 2.核心原理: 每次鼠标移动,我们都会获得最新的鼠标坐标, 把这个x和y坐标做为图片的top和left 值就可以移动图片 var x = e.pageX; var y = e.pageY; console.log('x坐标是' + x, 'y坐标是' + y); //3 . 千万不要忘记给left 和top 添加px 单位 pic.style.left = x - 50 + 'px'; pic.style.top = y - 40 + 'px'; }); </script> </body> </html>