JS原生代码实现鼠标移动图片随之移动效果(另加点击改变图片效果)

来源:互联网 发布:反转链表 非递归 java 编辑:程序博客网 时间:2024/05/16 01:43

以下是源代码

<!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.onload=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.onmousemove=function(){GetMouse(event);}    // 注册鼠标按下事件    ele.onmousedown=function(){ChangeBg("Img","img/1.gif");}    //注册鼠标弹回事件    ele.onmouseup=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>



0 0
原创粉丝点击