当窗口滚动到另一个元素时显示一个新元素

时间:2013-02-02 15:27:39

标签: jquery css fixed

我的jquery代码似乎遇到了一些问题,一旦用户滚动浏览页面中的某个特定元素,然后再向上滚动它就会让我的克隆导航进入视图。

我写的jquery代码是:

$(window).scroll(function() {
var homeHeight = $('#header').outerHeight() + $('.homeIntro').outerHeight();
var scrollPosition = $(this).scrollTop(); 
if( homeHeight <= scrollPosition ) {
    $('#clonedHeader').animate({'top': '0'}, 300);      
} else {
    $('#clonedHeader').animate({'top': '-100px'}, 300); 
}

});

这是一个小提琴:http://jsfiddle.net/ABdLh/

所以当你滚动浏览homeIntro部分时,克隆的标题会滑入视图,这就是我想要的想法,但它不会发生在我身上!

任何帮助将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:1)

我以前忽略了一些代码。只需添加.stop() - 方法即可使其正常工作:

if(homeHeight <= scrollPosition) {
    $('#clonedHeader').stop().animate({'top': '0'}, 300);      
} else {
    $('#clonedHeader').stop().animate({'top': '-100px'}, 300); 
}

试试here

答案 1 :(得分:1)

是的(jQuery没有被选中)是它无法工作的核心问题。但是有一些建议 -

像这样复制html标记非常糟糕。您应该使用jQuery / CSS来调整标题在各种滚动位置的样子。

此外,如果您在Chrome / Firefox中使用控制台,它可能会帮助您调试一下 - 它会在没有jQuery的情况下立即给您带来错误。如果你在这里打开我的小提琴,我在那里留下了console.log()语句,以显示基于滚动触发函数的位置。

动画这样的标题会引发一系列问题。如果您快速向上和向下滚动,使用jQuery动画可能会导致构建问题,这可能导致同一页面同时出现在页面上。 注意 - 您提到的停止方法对此有帮助,但对于大多数动画问题(特别是悬停),它是不够的,您应该查看像'HoverIntent'这样的插件。 < / p>

最后,在一个不断更新的函数之外声明+计算尽可能多的变量的好习惯 - 你不需要不断重新计算你要比较的标题的高度,它将是一个固定的数字。

// this height will be the same, you dont need to constantly calculate it on scroll
var homeHeight = $('#header').outerHeight() + $('.homeIntro').outerHeight(),
    scrollPosition;

$(window).on('scroll', function () {
    scrollPosition = $(this).scrollTop();
    animateHeight(scrollPosition);
});

function animateHeight(scrollPosition) {
    if (scrollPosition >= homeHeight) {
        console.log('yes');
        $('#clonedHeader').animate({
            'top': '0'
        }, 300);
    } else {
        console.log('no');
        $('#clonedHeader').animate({
            'top': '-100px'
        }, 300);
    }
}

http://jsfiddle.net/ndreckshage/ecUAc/

相关问题