【问题标题】:jQuery image hover effectjQuery图像悬停效果
【发布时间】:2011-05-08 20:24:53
【问题描述】:

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

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

基本上,如果您知道有一个已经构建的 jQuery 插件可以做到这一点,我会很乐意使用它,如果没有,我的公式的任何帮助将不胜感激。这就是我在数学课上不专心所得到的:)

提前致谢。

麦克尔

【问题讨论】:

    标签: javascript jquery css image hover


    【解决方案1】:

    总的来说,我认为这就是您要寻找的:

    $.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 对象,无需继续包装它们
    • 无需在mouseenter 上绑定mousemove(它会重新绑定)mousemove 只会在您在里面时出现。

    【讨论】:

    • 除了慢慢停下来之外,它与示例不完全相同。我无法停止描述它,但有些不对劲。
    • @Glenn - 它没有缓动,它绝对是一个更简化的版本,我只是在展示如何修复当前代码:)
    • 添加缓动比较复杂?
    • @Maikel - 当然,你必须计算一段时间内的鼠标速度......但对于一个小图像,我认为它不值得。
    • 这很奇怪.. 但这个例子似乎对我在 Firefox 上不起作用。 new_xnew_y 在 mousemove 事件中返回 NaN
    【解决方案2】:

    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 事件处理程序必须尽可能高效。它的限制性稍强一些,因为您需要知道尺寸,但我认为可以轻松更改代码以使用 imgs 可以轻松计算尺寸。

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

    【讨论】:

    • 应该注意这对原始版本有一些限制,例如您需要知道尺寸。话虽如此,对于许多情况来说,这是一个不错的选择,+1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2014-05-25
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多