jQuery图像悬停效果

时间:2010-11-12 02:37:36

标签: javascript jquery css image hover

我正在尝试使用jQuery实现this effect

我写了一些代码,但它有问题(转到右下角的corder,你会看到)。
check it out

基本上,如果有一个已经建立的jQuery插件,你知道这样做,我会很高兴使用它,如果没有,任何帮助我的公式将不胜感激。这是我在数学课上没有注意的结果:)

提前致谢。

Maikel

2 个答案:

答案 0 :(得分:7)

总的来说,我认为这就是你要找的东西:

$.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 });
            });
        }
    });
}

You can test it here

值得注意的变化:

  • new_xnew_y应按 images 高度/宽度划分,而不是容器的高度/宽度,它更宽。
  • this已经是$.fn.plugin函数中的jQuery对象,无需包装它。
    • ip也是jQuery对象,不需要继续包装它们
  • 无需在mousemove上绑定mouseenter(重新绑定)mousemove只会在您进入内部时发生。

答案 1 :(得分:3)

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,可以很容易地计算尺寸。

这是一个简单的演示:http://www.jsfiddle.net/yijiang/fq2te/1/

相关问题