悬停时的背景位置动画

Background position animation on hover

本文关键字:位置 动画 背景 悬停      更新时间:2023-09-26

我有一个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

终于解决了。

查找小提琴演示

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