如何在某个滚动位置或元素可见时为 css 'top' in jQuery 设置动画?

How to animate css 'top' in jQuery at a certain scroll location or when an element is visible?

我有一个 scrolltotop 图标,当 window 向下滚动一点时会出现。问题是当 window 滚动到页面底部时它与我不想要的 div 重叠。

我想让 scrolltotop 的顶部位置稍微向上移动一点,以避免在 window 一直滚动到底部时与 div 发生碰撞

这是我目前的情况:https://jsfiddle.net/qn6h9qad/

jQuery:

    //Scroll to top animate in
$(window).scroll(function(){
    if ($(this).scrollTop() < 300) {
        $('.scrollToTop').fadeOut(1000).css({right:-70});

    } else {
        $('.scrollToTop').fadeIn(1000).css({right:20});
    }
});

//Click event to scroll to top
$('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},1000);
    return false;
});

尝试

//Scroll to top animate in
$(window).scroll(function(){
    if ($(this).scrollTop() < 300) {
        $('.scrollToTop').stop(true, true).fadeOut(1000)
        .css({right:-70, bottom:"20px"});

    } else {
        $('.scrollToTop').fadeIn(1000)
        .css({right:20, bottom:"40px"});
    }
});

//Click event to scroll to top
$('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},1000);
    return false;
});

jsfiddle https://jsfiddle.net/qn6h9qad/4/

您需要为 window 上的滚动事件添加额外的条件:

if(($(this).scrollTop() + $(this).height()) > $('.projnav').position().top){
    $('.scrollToTop').css(bottom, 40);
}
else{
    $('.scrollToTop').css(bottom, 20);
}

要使动画流畅,只需添加:

.scrollToTop{
    transition: all .5s;
}

Fiddle 工作:http://jsfiddle.net/qn6h9qad/5/