案例:当鼠标移动时返回鼠标当前坐标
<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> div{ border: 2px solid green; margin-top: 10px; } #box1{ height: 100px; width: 500px; } #box2{ height: 20px; width: 500px; } </style> <script> window.onload = function(){ //分别找到两个盒子 var box1 = document.getElementById('box1'); var box2 = document.getElementById('box2'); //给box1绑定鼠标移动事件 box1.onmousemove = function(event){ //返回鼠标x轴 var x = event.clientX; //返回鼠标y轴 var y = event.clientY; //将x,y写入到box2中 box2.innerHTML = "x="+ x +" y="+ y; } } </script> </head> <body> <div id="box1"></div> <div id="box2"></div> </body> </html>
常见的鼠标事件属性和方法