悬停时的背景位置动画

Background position animation on hover

我有一个 div1,它通过 jquery 为鼠标悬停方向的背景位置设置动画。

但它工作正常。它的方向不对,我希望它能在 div.

上的每一次鼠标悬停时起作用

查找jsfiddle

代码:

$(function() {
    $(".mainCont").hover(function(e) {
            // $(this).addClass("hoverOnce");
        var edge = closestEdge(e.pageX, e.pageY, $(this).width(), $(this).height());
    }, function(){
           $(this).removeClass('top right bottom left');
         // $(this).removeClass("hoverOnce"); 
    });
});

function closestEdge(x,y,w,h) {
        var topEdgeDist = distMetric(x,y,w/2,0);
        var bottomEdgeDist = distMetric(x,y,w/2,h);
        var leftEdgeDist = distMetric(x,y,0,h/2);
        var rightEdgeDist = distMetric(x,y,w,h/2);
        var min = Math.min(topEdgeDist,bottomEdgeDist,leftEdgeDist,rightEdgeDist);
        switch (min) {
            case leftEdgeDist:
                $(".hoverOnce").addClass("left");
            case rightEdgeDist:
                $(".hoverOnce").addClass("right");
            case topEdgeDist:
                $(".hoverOnce").addClass("top");
            case bottomEdgeDist:
                $(".hoverOnce").addClass("bottom");
        }
}

function distMetric(x,y,x2,y2) {
    var xDiff = x - x2;
    var yDiff = y - y2;
    return (xDiff * xDiff) + (yDiff * yDiff);
}

您在背景中使用的这张图片的尺寸是 700x500:

http://thesis2010.micadesign.org/kropp/images/research/bird_icon.png

我认为,如果您将这些设置添加到 .mainCont,这将为您提供所需的结果:

width: 700px; 
height: 500px;
position: absolute;

例如:

.mainCont {
    width: 700px;
    height: 500px;
    background: url(http://thesis2010.micadesign.org/kropp/images/research/bird_icon.png) no-repeat center center;
    transition: all 0.5s ease-in-out;
    margin: 100px auto;
    position: absolute;
}

Fiddle

终于解决了

find fiddle demo

$('.mainCont').hover(function(e){
        var dir = determineDirection($(this), {x: e.pageX, y: e.pageY});
        $(this).addClass('direction_'+dir);
    }, function() {
        $(this).removeClass('direction_3 direction_1 direction_2 direction_0');
    });

function determineDirection($el, pos){
    var w = $el.width(),
        h = $el.height(),
        x = (pos.x - $el.offset().left - (w/2)) * (w > h ? (h/w) : 1),
        y = (pos.y - $el.offset().top  - (h/2)) * (h > w ? (w/h) : 1);

    return Math.round((((Math.atan2(y,x) * (180/Math.PI)) + 180)) / 90 + 3) % 4;
}