JS:跟随鼠标移动的图片,兼容IE与DOM浏览器(已在实际中用懂啊)

来源:互联网 发布:illuststudio mac 编辑:程序博客网 时间:2024/06/05 05:06


http://blog.sina.com.cn/s/blog_48e6792c0100z8ie.html

基本设计思路:

   1、首先捕捉鼠标的移动,获取鼠标当前位置坐标(clientX和clientY属性),这一点通过事件对象得到;

   2、获取图片当前的位置;

   3、比较图片当前位置与鼠标当前位置坐标,修改图片当前位置(left和top属性),移动图片。移动时,如果图片当前位置坐标大于鼠标当前位置坐标,则将图片位置坐标减小,否则将图片位置坐标增加,直至图片坐标与鼠标坐标相等。

 

代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>跟随鼠标移动的图片</title><script type="text/javascript">var mouse_x = 0;var mouse_y = 0;  //鼠标坐标var img_x =0;var img_y = 0;  //图片坐标var move_to_x = 0;var move_to_y = 0;  //移动目标位置坐标var step = 5;            //图片每次移动距离var interval = 10;         //间隔时间移动var scroll_x;var scroll_y; //页面在水平、垂直方向上已经滚动的距离var image_width;var image_height;function getPos(e){   scroll_x = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft; scroll_y = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop; //获取窗口大小 win_width = windows.innerWidth ? windows.innerWidth : document.body.clientWidth; win_height = windows.innerHeight ? windows.innerHeight : document.body.clientHeight;   //图片尺寸 image_width =  document.getElementByIdx_x("image_id").width; image_height = document.getElementByIdx_x("image_id").height;   //获取鼠标所在位置 e = e ? e : event mouse_x = e.clientX; mouse_y = e.clientY;  //计算move_to_x,move_to_y值,为图片指定移动边界,避免图片移动到窗口外 if(mouse_x < 2) {  move_to_x = scroll_x + 2; } else if(mouse_x > win_width - image_width - 20) {  move_to_x = scroll_x + win_width - image_width - 20; } else {  move_to_x = scroll_x + mouse_x; }  if(mouse_y < 2) {  move_to_y = scroll_y + 2; } else if(mouse_y > win_height - image_height - 20) {  move_to_y = scroll_y + win_height - image_height - 20; } else {  move_to_y = scroll_y + mouse_y; }  return;           //移动图片}function moveImage(){ var img = document.getElementByIdx_x("div_id"); //图片当前位置 img_x = parseInt(img.style.left); img_y = parseInt(img.style.top);  //比较目标位置与图片当前位置,若不等,将img_x按 step距离计算,重新赋值给img.style.left; if(Math.abs(move_to_x - img_x) > 5) {  img_x += step * ((move_to_x - img_x > 5) ? 1 : -1);  img.style.left = img_x + "px"; }    if(Math.abs(move_to_y - img_y) > 5) {  img_y += step * ((move_to_y - img_y > 5) ? 1 : -1);  img.style.top = img_y + "px"; } setTimeout("moveImage()",interval);}</script></head><body id="id_body"  onload="moveImage()" onmousemove="getPos(event)"><div id="div_id" style="position:absolute; left:0px; top:0px; z-index:10;"><img id="image_id" src="images/gkbm.gif" /></div><table height="1000px" style="background:#ccc"><tr><td></td></tr></table></body></html>


0 0