跟踪鼠标位置以移动图像
我有一个非常简单的页面。
造型也很简单。
#index {position:relative;} #index img {position:absolute; bottom:10%; right:10%; width:100%;}
我使用%,因此如果浏览器窗口resize,可以按比例调整图像大小。 不要管那个。
问题是,我正在尝试模拟这个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范围),图像将略微向左移动,但当我将鼠标从右移动到中心时,图像仍然向左移动! 它应该向右移动到其原始位置,但它不会因为网络不知道鼠标是从右向中移动还是从中向右移动。
有帮助吗?
我很快就玩弄了它,它没有使用.each循环显示图像,但可能会帮助你进行鼠标移动计算。 运动分频器应该基于z-index,而不是硬编码,因为较低的z-index项目移动得更多。
在此演示中,在鼠标hover之前,初始放置不正确。
在这里演示: http : //jquerydoodles.com/stack_question.html
希望有所帮助!
CSS:
#index { position: relative; border: 2px solid #ccc; height: 400px; } #index img { position: absolute; background-color: #fff; border: 1px solid #666; padding: 6px; } #image1 { z-index: 3; } #image2 { z-index: 2; width: 150px; left: 200px; } #image3 { z-index: 1; width: 100px; left: 300px; } #image4 { z-index: 2; width: 150px; left: -200px; } #image5 { z-index: 1; width: 100px; left: -300px; }
HTML
JQUERY:
$(document).ready(function($){ $("#index").mousemove(function(e){ var mouseX = e.pageX - $('#index').offset().left; var mouseY = e.pageY - $('#index').offset().top; var totalX = $('#index').width(); var totalY = $('#index').height(); var centerX = totalX / 2; var centerY = totalY / 2; var shiftX = centerX - mouseX; var shiftY = centerY - mouseY; var startX = ($('#index').width() / 2) - ($('#image1').width() / 2); var startY = ($('#index').height() / 2) - ($('#image1').height() / 2); $('#image1').css('z-index') ; $('#image1').css({ 'left': startX + (shiftX/10) + 'px', 'top': startY + (shiftY/10) + 'px' }); $('#image2').css({ 'left': startX + 220 + (shiftX/8) + 'px', 'top': startY + 50 + (shiftY/8) + 'px' }); $('#image3').css({ 'left': startX + 370 + (shiftX/6) + 'px', 'top': startY + 60 + (shiftY/6) + 'px' }); $('#image4').css({ 'left': startX - 100 + (shiftX/8) + 'px', 'top': startY + 50 + (shiftY/8) + 'px' }); $('#image5').css({ 'left': startX - 150 + (shiftX/6) + 'px', 'top': startY + 60 + (shiftY/6) + 'px' }); }); });