一对随鼠标转动的眼睛

算法很简单,但设计很巧妙,值得收藏。

Html 代码

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 2         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml">
 4 <head>
 5     <title>Mouse Movements</title>
 6     <link type="text/css" rel="stylesheet" href="script06.css" />
 7     <script type="text/javascript" src="script06.js"></script>
 8 </head>
 9 <body>
10     <img src="images/circle.gif" alt="left eye" width="24" height="25" id="lEye" />
11     <img src="images/circle.gif" alt="right eye" width="24" height="25" id="rEye" />
12     <img src="images/lilRed.gif" alt="left eyeball" width="4" height="4" id="lDot" />
13     <img src="images/lilRed.gif" alt="right eyeball" width="4" height="4" id="rDot" />
14 </body>
15 </html>
View Code

JS 代码

 1 document.onmousemove = moveHandler;
 2 
 3 function moveHandler(evt) {
 4     if (!evt) {
 5         evt = window.event;
 6     }
 7     animateEyes(evt.clientX, evt.clientY);
 8 }
 9 
10 function animateEyes(xPos, yPos) {
11     var rightEye = document.getElementById("rEye");
12     var leftEye = document.getElementById("lEye");
13     var rightEyeball = document.getElementById("rDot").style;
14     var leftEyeball = document.getElementById("lDot").style;
15 
16     leftEyeball.left = newEyeballPos(xPos, leftEye.offsetLeft);
17     leftEyeball.top = newEyeballPos(yPos, leftEye.offsetTop);
18     rightEyeball.left = newEyeballPos(xPos, rightEye.offsetLeft);
19     rightEyeball.top = newEyeballPos(yPos, rightEye.offsetTop);
20 
21     function newEyeballPos(currPos, eyePos) {
22         return Math.min(Math.max(currPos, eyePos+3), eyePos+17) + "px";
23     }
24 }
View Code

CSS 代码

 1 body {
 2     background-color: #FFFF99;
 3 }
 4 
 5 #lEye, #rEye {
 6     position: absolute;
 7     top: 100px;
 8 }
 9 
10 #lDot, #rDot {
11     position: absolute;
12     top: 113px;
13 }
14 
15 #lEye {
16     left: 100px;
17 }
18 
19 #rEye {
20     left: 150px;
21 }
22 
23 #lDot {
24     left: 118px;
25 }
26 
27 #rDot {
28     left: 153px;
29 }
View Code

图片

  

posted @ 2015-03-29 16:01  壬子木  阅读(118)  评论(0)    收藏  举报