jQuery 图片悬停效果

5

我正在尝试使用jQuery实现这种效果

我写了一些代码,但它有缺陷(移动到右下角就会看到)。
请查看

基本上,如果您知道已经构建好的jQuery插件可以做到这一点,我将非常高兴使用它。否则,任何对我的公式的帮助都将不胜感激。这就是我没有在数学课上注意的结果 :)

提前致谢。

Maikel

2个回答

6
总的来说,我认为这就是你正在寻找的内容:
$.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_xnew_y 应该除以图片的高度/宽度,而不是容器的高度/宽度,因为图片比较宽。
  • this$.fn.plugin 函数中已经是一个 jQuery 对象了,不需要再次包装它。
    • ip 也是 jQuery 对象,不需要继续包装它们。
  • 不需要在 mouseenter 上绑定 mousemove(重新绑定),mousemove 只会在你进入时发生。

除了慢慢停下来之外,它并不完全像例子。我无法准确描述,但感觉有些不对劲。 - user372743
1
@Glenn - 它没有缓动效果,它肯定是一个更简化的版本,我只是展示如何修复当前的代码 :) - Nick Craver
添加缓动是否更复杂? - Maikel
@Maikel - 当然,你需要在一段时间内计算鼠标速度...但对于一个小图像来说,我认为这不值得。 - Nick Craver
@Nick,感谢你的帮助,但你知道为什么当你移动到边缘时它会有点出现问题吗?这种情况在我的Chrome浏览器上发生。 - Maikel
显示剩余5条评论

3

尼克·克拉弗比我早大约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

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


需要注意的是,这个版本相对于原版有一些限制,例如你需要知道尺寸。话虽如此,在许多情况下它是一个很好的替代选择,加一。 - Nick Craver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接