在某些滚动后更改侧边栏

时间:2013-07-07 19:38:55

标签: javascript sidebar

我正在尝试让我的侧边栏正常运行,直到发生了一定量的滚动(它已滚过第一个子div元素),然后修复到位。

作为测试,我尝试将其更改为空白。但它没有任何影响。

<script type="text/javascript">
    var side_offset_top = $('#side').offset().top;
    var side = function(){
        var scroll_top = $(window).scrollTop();
        if (scroll_top > side_offset_top) { 
            document.getElementById('side').innerHTML = ''; //blank to test
        } else {
        }
    };
    side();
    $(window).scroll(function() {
        side();
    });
});
</script>

我是JavaScript新手,所以我很感激有人帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我猜你正在使用jQuery,因为我看到$

在代码的最后一行有一个额外的});,所以除非是复制粘贴错误,否则你应该删除它。

然后尝试将代码放在$(document).ready()处理程序中。当你检查它的偏移时,$('#side')可能还没有在DOM中。

像(未经测试)的东西:

$(document).ready(function(){
    var side_offset_top = $('#side').offset() && $('#side').offset().top;
    var side = function(){
        var scroll_top = $(window).scrollTop();
        if (scroll_top > side_offset_top) { 
            $('#side').html(''); // using jQuery .html
        }
    };
    side();
    $(window).on('scroll', function() { // consider using .on here instead
        side();
    });
});
编辑:哎呀! offset()。top()应该是offset()。top