[英]jQuery image hover effect
总的来说,我认为这就是你要找的东西:
$.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对象,不需要继续包装它们 mousemove
上mouseenter
(其重新绑定)将mousemove
时,你在里面无论如何才会发生。 尼克克拉弗大约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,其大小可以很容易地计算。
一个简单的演示: http : //www.jsfiddle.net/yijiang/fq2te/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.