以下是源代码
<!DOCTYPE html> <html> <head> <title>图片跟着鼠标走</title> <style type="text/css"> *{ margin:0px; padding:0px;} #Img{ position:absolute; top:0px; left:0px; width: 200px;height: 150px} #Main{ background: url(11111.jpg); width:999px; height:444px;}/*此处直接使用background-imagh会直接无效*/ </style> <script type="text/javascript"> window.οnlοad=Main; //全局坐标变量 var x=""; var y=""; //定位图片位置 function GetMouse(oEvent) { x=oEvent.clientX; y=oEvent.clientY; if(x>900&&y>400) return;//此处设置图片不运动的区域 document.getElementById("Img").style.left=(parseInt(x)-100)/2+"px"; document.getElementById("Img").style.top=y/2+"px";//除以5是改变一下速度 } //入口 function Main() { var ele=document.getElementById("Main"); //注册鼠标移动事件 ele.οnmοusemοve=function(){GetMouse(event);} // 注册鼠标按下事件 ele.οnmοusedοwn=function(){ChangeBg("Img","img/1.gif");} //注册鼠标弹回事件 ele.οnmοuseup=function(){ChangeBg("Img","img/2.jpg");} } //图片变化 function ChangeBg(id,url) { document.getElementById(id).src=url; } </script> </head> <body > <div id="Main" ><img src="img/1.gif" id="Img"></div> </body> </html>
