jQuery图片悬停效果 [英] jQuery image hover effect

查看:97
本文介绍了jQuery图片悬停效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery实现此效果

I'm trying to achieve this effect with jQuery.

我写了一些代码,但它是buggy(移动到右下角,你会看到)。

检查它

I wrote some of the code, but it's buggy (move to the bottom-right corder and you'll see).
check it out

基本上,如果有一个已经构建的jQuery插件,你知道这样做,我会非常高兴使用它,如果没有,任何帮助我的公式将不胜感激。 )

Basically, if there's an already-built jQuery plugin that you know of that does this, I'd be very happy using it, if not, any help with my formula would be appreciated. This is what I get for not paying attention in Maths classes :)

提前感谢。

Maikel

推荐答案

总体来说,我认为这是你要找的:

Overall I think this is what you're looking for:

$.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 应按照图片 height / width $ 已经是中的jQuery对象, $ .fn.plugin 函数,无需换行。

    • i p

    • 不需要绑定 mousemove c> mouseenter (重新绑定) mousemove 只会出现在你还在里面时。

    • new_x and new_y should be divided by the images height/width, not the container's height/width, which is wider.
    • this is already a jQuery object in a $.fn.plugin function, no need to wrap it.
      • i and p were also jQuery objects, no need to keep wrapping them

      这篇关于jQuery图片悬停效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆