<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>苹果菜单(每个图片中心点的坐标)</title> <style> body{ margin:0; padding:0; } div{ position: absolute; bottom: 0; width: 100%; text-align: center; background: pink; } div img{ width: 64px; } </style> <script> window.onload = function(ev){ var oDiv = document.getElementById('div1'); var oPut = document.getElementsByTagName('input'); var Oimg = oDiv.getElementsByTagName('img'); var oEvent = ev||event; for (var i = 0; i < Oimg.length; i++) { var x = Oimg[i].offsetLeft+Oimg[i].offsetWidth/2; var y = Oimg[i].offsetTop+oDiv.offsetTop+Oimg[i].offsetHeight/2; var a = oEvent.clientX - x; /*鼠标距图片中心店的横向距离*/ var b = oEvent.clientY - y; /*鼠标距图片中心店的纵向距离*/ alert(oEvent.clientX); var dis = Math.sqrt(a*a+b*b); /*鼠标点距图片中心点两点之间c的距离*/ oPut[i].value = dis; } }; </script> </head> <body> <input type="text" /> <input type="text" /> <input type="text" /> <input type="text" /> <input type="text" /> <div id="div1"> <img src="1.png" /> <img src="2.png" /> <img src="3.png" /> <img src="4.png" /> <img src="5.png" /> </div> </body> </html>
在onload里,js文件一加载便被执行,所以取不到鼠标的clientX和clientY,window.onload需要改为document.onmousemove,当移入页面的时候执行