我有一个非常简单的页面。跟踪鼠标移动图像的位置
<div id="index">
<img />
</div>
造型也很简单。
#index {position:relative;}
#index img {position:absolute; bottom:10%; right:10%; width:100%;}
我使用%,因此如果浏览器窗口调整大小,图像可以按比例调整大小。不要管那个。
问题是,我试图效仿这个Flash网站上的效果:http://www.tatogomez.com/因此,图像位于屏幕的右下角。当我将鼠标移到左上角时,图像会略微向右下方移动一点。当我将鼠标移动到中心位置时,图像将恢复到其原始位置。所以它有点像我给予阴影/光照效果,其中鼠标是光线,图像是对象,除了我只需要移动动画。
我的代码是这样的
$(document).ready(function($){
$('#index').mousemove(
function(e){
$(this).children('img').each(
function(){
var totalWidth = $(window).width();
var totalHeight = $(window).height();
var centerX = $(window).width()/2;
var centerY = $(window).height()/2;
var mouseX = e.pageX;
var mouseY = e.pageY;
var current_top = $(this).offset().top;
var current_left = $(this).offset().left;
var myX = (centerX-mouseX)/centerX;
var myY = (centerY-mouseY)/centerY;
var cssObj = {
'left': current_left + myX + 'px'
'top': current_top + myY + 'px'
}
$(this).css(cssObj);
}
);
}
);
});
,所以如果我移动鼠标相对于屏幕的中心。所以基本上是这样的:
centerX = 700 (i use resolution 1400);
currentLeft = ~200 (the offset left of my image)
So if my mouse position is at 700-1400, then the myX will be 700(centerX) - 900(mouse position) = -200/700 = ~ -0.3. Add it into the css calculation, the left will be current_left(200) + myX(-0.3) px = 197.7px.
然后我意识到,如果我从中央到右侧(700-1400范围)移动我的鼠标,图像将略微向左移动,但是当我移动我的鼠标从中心的权利,图像仍然向左移动!它应该向右移动到原来的位置,但这并不是因为网络不知道鼠标是从右向中心还是从中心向右移动。
任何帮助?