jquery return 元素到其原始位置

jquery return element to its original position

我试图让 div 在鼠标悬停时向上扩展,然后 return 在鼠标移开时扩展到其原始高度。很简单。 div 是绝对定位的,bottom: 0,因此它紧贴其父级的底部。问题是我无法控制 div 中内容的长度,因此最高值设置为自动。

因此,我需要计算实际的顶部位置,然后将该值传递给 hover() 中处理鼠标移出动画的第二个函数,以恢复其原始高度。

    $('#blog3 .blog-grid li').hover(
    function () { // mouse over
        // calculate .content-box top position
        var offset = $(this).find(".content-box").offset().top - $(this).find(".content-box").parent().offset().top;

        // darken the box
        $(this).find(".content-box").css("background-color", "rgba(0,0,0,0.5)").animate({
            queue: false,
            duration: 500
        });

        // expand the content div
        $(this).find(".content-box").stop(true,true).animate({
            top: 0,
        }, {
            queue : false,
            duration : 500
        });

        $(this).find("p").fadeIn("slow");
        $(this).find(".read-more").stop(true,true).fadeIn("slow");
    }, 
    function () { // mouse out
        $(this).find(".content-box").css("background-color", "transparent").animate({
            queue: false,
            duration: 500
        });

        $(this).find(".content-box").stop(true,true).animate({
            top: offset + 'px', // <-- restore to original position
        }, {
            queue : false,
            duration : 500
        });

        $(this).find("p").stop(true,true).fadeOut("slow");
        $(this).find(".read-more").stop(true,true).fadeOut("slow");
    }
);

当然,问题是我不能将 'offset' 变量传递给第二个(mouseout)函数,也不能将 'offset' 声明为全局变量,因为它需要在悬停时计算。

我确定一定有另一种方法可以将该数字传递给第二个函数,但我似乎无法弄清楚...

回答了我自己的问题 ;)

设置'offset'为全局变量,然后在mouseover函数内部进行位置计算

var offset = null;
$('#blog3 .blog-grid li').hover(
    function () {
        //get .content-box top position
        offset = $(this).find(".content-box").offset().top - $(this).find(".content-box").parent().offset().top;

        // darken the box
        $(this).find(".content-box").css("background-color", "rgba(0,0,0,0.5)").animate({
            queue: false,
            duration: 500
        });

        // initialize position
        $(this).find(".content-box").css("top", offset);

        // expand the content div
        $(this).find(".content-box").stop(true,true).animate({
            top: 0,
        }, {
            queue : false,
            duration : 500
        });

        $(this).find("p").fadeIn("slow");
        $(this).find(".read-more").stop(true,true).fadeIn("slow");
    }, 
    function () {
        $(this).find(".content-box").css("background-color", "transparent").animate({
            queue: false,
            duration: 500
        });

        $(this).find(".content-box").stop(true,true).animate({
            top: offset + 'px',
        }, {
            queue : false,
            duration : 500
        });

        $(this).find("p").stop(true,true).fadeOut("slow");
        $(this).find(".read-more").stop(true,true).fadeOut("slow");
    }
);