鼠标位置交互图像



我目前有一个图像,根据鼠标位置更新。查看[http://www.fore6.com/?p=533][1]

[1]: http://www.fore6.com/?p=533让你明白我的意思。

问题是,我有多个图像,我需要应用这个,和每个图像需要动画独立于其他。在这一刻,他们都在同一时间活动,即;它们需要独立动画,因为每个图像的鼠标位置都不同!

我可以通过为每个图像重复函数并更改变量来获得它的工作,但这是一个可怕的大量代码。我如何在一个函数中做到这一点?

我猜我可能需要将每个图像放入数组或使用$(this),但似乎不知道如何实现它。

任何帮助都将非常感激。我使用的代码如下:

var imageX = null;
var imageY = null;
imageX = $('.anim-photo').offset().left;
imageY = $('.anim-photo').offset().top;
$(document).mousemove(function(event) {
    var mousePos = new Array(event.pageX, event.pageY);
    interact(mousePos, ["0px", "-288px", "-576px"]);
})
function interact(mouseCord, aniCord) {
    if (mouseCord[0] < imageX && mouseCord[1] < imageY){ // Box-1
    $(".anim-photo").css("background-position", aniCord[0]+" 0px");
} else if (mouseCord[0] > imageX && mouseCord[0] < imageX+285 && mouseCord[1] < imageY){ // Box-2
    $(".anim-photo").css("background-position", aniCord[1]+" 0px");
} else if (mouseCord[0] > imageX+285 && mouseCord[1] < imageY){ // Box-3
    $(".anim-photo").css("background-position", aniCord[2]+" 0px");
} else if (mouseCord[0] < imageX && mouseCord[1] > imageY && mouseCord[1] < imageY+357){ // Box-4
    $(".anim-photo").css("background-position", aniCord[0]+" -360px");
} else if (mouseCord[0] > imageX && mouseCord[0] < imageX+285 && mouseCord[1] > imageY && mouseCord[1] < imageY+357){ // Box-5
    $(".anim-photo").css("background-position", aniCord[1]+" -360px");
}else if (mouseCord[0] > imageX+285 && mouseCord[1] > imageY && mouseCord[1] < imageY+357){ // Box-6
    $(".anim-photo").css("background-position", aniCord[2]+" -360px");
} else if (mouseCord[0] < imageX && mouseCord[1] > imageY+357){ // Box-7
    $(".anim-photo").css("background-position", aniCord[0]+" -720px");
} else if (mouseCord[0] > imageX && mouseCord[0] < imageX+285 && mouseCord[1] > imageY+357){ // Box-8
    $(".anim-photo").css("background-position", aniCord[1]+" -720px");
} else if (mouseCord[0] > imageX+285 && mouseCord[1] > imageY+357){ // Box-9
    $(".anim-photo").css("background-position", aniCord[2]+" -720px");
}
};

你只需要一个像这样的图像元素:

<img id="face" src="face-follower/0.jpg" alt="face">

假设我们有一组名称为:000.jpg, 001.jpg和…中:

  1. 第一个num表示鼠标位置为1时在中间上方,为0时在中间下方。
  2. 第二个num表示鼠标在中间位置的左边为0,在中间位置的右边为1。
  3. 第三num以22.5度角将每四分之一页划分为4个部分

获取图像的中心,并检查光标与图像中心的位置。然后根据位置创建image的名称:

var element = $('#face');
var top = element.offset().top + element.height()/2;
var left = element.offset().left + element.width()/2;
var a = 0
, b = 0 
, c = 0;
$('body').mousemove(function()
{
var x=Math.floor(event.clientX - left);
var y=Math.floor(event.clientY - top);
if(x > 0)
  a = 1;
else if(x < 0)
  a = 0;
if(y > 0)
  b = 0;
else if(y < 0)
  b = 1;
if(Math.abs(x) > Math.abs(y))
{
  c = 2;
  if(Math.abs(x)>Math.abs(y)*2.4)
    c = 3;
}
else if(Math.abs(y) > Math.abs(x))
{
  c = 1;
  if (Math.abs(y)>Math.abs(x)*2.4)
    c = 0;
}

现在你有完整的3个字符的图像名称,改变它的来源element.attr("src"、"face-follower/' + a + b + c + . jpg);});
工作样本

最新更新