偏移javascript滚动:无法读取未定义错误的属性“顶部”

时间:2014-11-13 01:30:29

标签: javascript jquery scroll undefined offset

我正在尝试使用此javascript将侧边栏导航设置为偏移并使用滚动变为粘性。错误是:

“无法读取未定义的属性'top'”

错误发生在var stickyNavTop = $('.toc').offset().top - 222;,它阻止其他js正常工作。

Example page using script

脚本:

// Sidebar Nav Sticky with Scroll
jQuery(document).ready(function() {  
    var stickyNavTop = $('.toc').offset().top - 222;
    var stickyEnd = $('.content').height() - 111; // stores height of .content element
    var praiseH = $('.praise').height(); //height of praise bar if present

    var stickyNav = function(){  
        var scrollTop = $(window).scrollTop();  

        if (scrollTop > stickyNavTop) {   
            $('.toc').addClass('sticky-nav'); 
            $('.content').css('float','right'); //needs float:right; applied due to .sticky-nav class being positioned
        } else {  
            $('.toc').removeClass('sticky-nav');
            $('.content').css('float','left');
        }

        if ($(window).scrollTop() >= (stickyEnd - praiseH) ) {
//          $('.toc').addClass('bottom'); removed for fadeIn/fadeOut
            $('.toc').fadeOut('slow');
        } else {
            $('.toc').fadeIn('slow');
        }

    };

    stickyNav();

    $(window).scroll(function() {  
        stickyNav();
    });

});

任何关于如何解决这个问题的帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用console.log()函数实际查看任何元素的本机属性。 我不知道你是否仅限于JQuery,但每次都有本机JavaScript解决方案;)

我发现了这个: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop

可能会有所帮助

答案 1 :(得分:0)

添加一个if语句,以查看我的.toc元素是否实际填充并存在,现在错误消失了,它可以在它应该的页面上运行。

谢谢!

if ($('.toc').length > 0) { 
    var stickyNavTop = $('.toc').offset().top - 222;
    var stickyEnd = $('.content').height() - 111; // stores height of .content element
    var praiseH = $('.praise').height(); //height of praise bar if present

    var stickyNav = function(){  
        var scrollTop = $(window).scrollTop();  

        //output test heights
//      $("#test").html($(window).scrollTop());
 //   $("#height").html(stickyEnd);
  //  $("#praise").html(footerH);

        if (scrollTop > stickyNavTop) {   
            $('.toc').addClass('sticky-nav'); 
            $('.content').css('float','right'); //needs float:right; applied due to .sticky-nav class being positioned
        } else {  
            $('.toc').removeClass('sticky-nav');
            $('.content').css('float','left');
        }

        if ($(window).scrollTop() >= (stickyEnd - praiseH) ) {
//          $('.toc').addClass('bottom'); removed for fadeIn/fadeOut
            $('.toc').fadeOut('slow');
        } else {
            $('.toc').fadeIn('slow');
        }

    };

    stickyNav();

    $(window).scroll(function() {  
        stickyNav();
    });
}