*{margin:0;padding:0;}
#face{position:relative;width:141px;height:185px;margin:100px auto 0;background:url(http://jayuh.com/wp-content/uploads/2013/04/head.png) no-repeat;}
#eyeLeft, #eyeRight{position:absolute;width:20px;height:20px;background:url(http://jayuh.com/wp-content/uploads/2013/04/ball.png) no-repeat;}
#eyeLeft{top:62px;left:30px}
#eyeRight{top:60px;left:96px;}
var faceLeft = document.getElementById("face").offsetLeft;
var faceTop = document.getElementById("face").offsetTop;
var x1 = document.getElementById("eyeLeft").offsetLeft + faceLeft;//左眼睛相对于浏览器的left值
var y1 = document.getElementById("eyeLeft").offsetTop + faceTop;//左眼睛相对于浏览器的top值
var x2 = document.getElementById("eyeRight").offsetLeft + faceLeft;
var y2 = document.getElementById("eyeRight").offsetTop + faceTop;
var radius = 10;//半径
document.onmousemove = function(ev) {
var oEvent = ev || event;
/**** 左眼睛开始 ****/
//返回鼠标坐标相对于demo的坐标
var x11 = oEvent.clientX - x1;
var y11 = -(oEvent.clientY - y1);
//返回X轴到点(y11,x11)的弧度说明:弧度的值在π到-π之间
var k1 = Math.atan2(y11, x11);
//返回k1的余弦值 * 半径 + demo初始化的X轴坐标说明:正弦、余弦返回的值在-1到1之间
var x111 = (Math.cos(k1) * radius + x1).toFixed(0);
//返回k1的正弦值 * 半径 + demo初始化的Y轴坐标
var y111 = (( - Math.sin(k1) * radius) + y1).toFixed(0);
//赋值
document.getElementById("eyeLeft").style.left = x111 - faceLeft + "px";
document.getElementById("eyeLeft").style.top = y111 - faceTop + "px";
/**** 左眼睛结束 ****/
//右眼睛原理同左眼睛
var x22 = oEvent.clientX - x2;
var y22 = -(oEvent.clientY - y2);
var k2 = Math.atan2(y22, x22);
var x222 = (Math.cos(k2) * radius + x2).toFixed(0);
var y222 = (( - Math.sin(k2) * radius) + y2).toFixed(0);
document.getElementById("eyeRight").style.left = x222 - faceLeft + "px";
document.getElementById("eyeRight").style.top = y222 - faceTop + "px";
};
一键复制
编辑
Web IDE
原始数据
按行查看
历史