如何编辑一个jQuery动画,使其出现在元素的中间

How do I edit a jQuery animation to appear in the middle of an element?

本文关键字:元素 中间 jQuery 编辑 何编辑 一个 动画      更新时间:2023-09-26

我使用这个代码从JS提琴创建一个网页上的元素淡出动画。现在,一旦整个元素在窗口中可见,元素就会淡入。有没有办法编辑这个,这样我就可以更快地触发淡出动画?理想情况下,淡出动画应该在只有一半元素可见而不是整个元素可见时触发。

下面是触发这个动画的JavaScript代码:
/* every time the window is scrolled ... */
 $(window).scroll( function(){
    /* check the location of each desired element */
    $('.fade-in').each( function(i){
        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();
        /* if the object is completely visible in the window, fade it in */
        if( bottom_of_window > bottom_of_object ){
            $(this).animate({'opacity':'1'},600);
        }
    });
});
});

bottom_of_object的值修改为低于原始高度的值

var bottom_of_object = $(this).offset().top + $(this).outerHeight() / 3; //we dived by 3 here at the end.

尝试在if部分或计算中减半你的bottom_of_objekt

 /* every time the window is scrolled ... */
     $(window).scroll( function(){
        /* check the location of each desired element */
        $('.fade-in').each( function(i){
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            /* if the object is completely visible in the window, fade it in */
            if( bottom_of_window > (bottom_of_object / 2) ){
                $(this).animate({'opacity':'1'},600);
            }
        });
    });
    });