jQuery图像悬停效果
问题描述:
我试图用jQuery实现this effect。jQuery图像悬停效果
我写了一些代码,但它是越野车(移到右下角,你会看到)。
check it out
基本上,如果有,你知道的,它这个,我会使用它,如果不是很高兴已经建成的jQuery插件,用我的公式任何帮助,将不胜感激。这是我在数学课上不注意的地方:)
在此先感谢。
Maikel
答
总的来说,我认为这是你在找什么:
$.fn.sexyImageHover = function() {
var p = this, // parent
i = this.children('img'); // image
i.load(function(){
// get image and parent width/height info
var pw = p.width(),
ph = p.height(),
w = i.width(),
h = i.height();
// check if the image is actually larger than the parent
if (w > pw || h > ph) {
var w_offset = w - pw,
h_offset = h - ph;
// center the image in the view by default
i.css({ 'margin-top':(h_offset/2) * -1, 'margin-left':(w_offset/2) * -1 });
p.mousemove(function(e){
var new_x = 0 - w_offset * e.offsetX/w,
new_y = 0 - h_offset * e.offsetY/h;
i.css({ 'margin-top':new_y, 'margin-left':new_x });
});
}
});
}
值得注意的变化:
-
new_x
和new_y
应由图像被划分高度/宽度,而不是在容器的高度/宽度,这是更宽。 -
this
已经是一个$.fn.plugin
函数中的jQuery对象,不需要包装它。-
i
和p
也jQuery的对象,没有必要继续它们包裹
-
- 没有必要对
mouseenter
结合mousemove
(这将重新绑定)时,你在里面反正mousemove
才会发生。
答
Nick Craver打了我约10分钟的答案,但这是我的代码,使用background-image
来定位图像,而不是实际的图像。
var img = $('#outer'),
imgWidth = 1600,
imgHeight = 1200,
eleWidth = img.width(),
eleHeight = img.height(),
offsetX = img.offset().left,
offsetY = img.offset().top,
moveRatioX = imgWidth/eleWidth - 1,
moveRatioY = imgHeight/eleHeight - 1;
img.mousemove(function(e){
var x = imgWidth - ((e.pageX - offsetX) * moveRatioX),
y = imgHeight - ((e.pageY - offsetY) * moveRatioY);
this.style.backgroundPosition = x + 'px ' + y + 'px';
});
的变量巨大量是有,因为mousemove
事件处理程序必须尽可能高效。它稍微有些限制,因为你需要知道尺寸,但我认为代码可以很容易地改变,以便与img
s一起工作,因为它的尺寸可以很容易地计算出来。
A的这个简单的演示:http://www.jsfiddle.net/yijiang/fq2te/1/
从慢慢来停止+0
应该注意的是,这对原始文件有一些限制,例如你需要知道尺寸。这就是说,这是很多情况下的好选择,+1。 – 2010-11-12 03:17:53
除此之外,它是不完全一样的例子。我不能放弃描述它,但有些事情是关闭的。 – 2010-11-12 02:54:31
感谢尼克,修正了它:) – Maikel 2010-11-12 02:56:52
@Glenn - 它没有缓动,它绝对是一个更简化的版本,我只是显示如何修复当前的代码:) – 2010-11-12 02:58:17