滚动侧边栏抛出 Javascript 错误“无法调用 null 的方法'偏移量'

Scrolling sidebar throws Javascript error "Cannot call method 'offset' of null

本文关键字:null 无法调用 方法 调用 偏移量 侧边栏 Javascript 错误 滚动      更新时间:2023-09-26

本质上,我正在研究一个侧边栏,只有在浏览器窗口到达它后才会滚动。

更新 2:

这是我目前正在使用的代码:

$(function() {
var $sidebar   = $("#sidebar"),
    $window    = $(window),
    offset     = $sidebar.offset(),
    topPadding = 15;
    $window.scroll(function() {
        if ($window.scrollTop() > offset.top) {
            $sidebar.addClass('fixed');
        } else {
            $sidebar.removeClass('fixed');
        }
    });
});

我不再收到错误,但是滑动不起作用。这里的这个小提琴显示了所需的效果,我的 CSS 完全相同:http://jsfiddle.net/dKDJz/647/

如果这段代码有效,你可能想要检查 2 件事

  • 将代码包装在就绪函数中

可能是您的代码在元素存在/呈现之前正在运行。在这种情况下,使用就绪函数包装您的代码

$(function() {
  // your code
});
  • 检查是否正在加载 jQuery 库文件。

如果您没有加载 jQuery 库文件,请将其添加到页面的标记中。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

您需要将选择器放在文档就绪包装器中。本质上,当您尝试运行选择器时,#sidebar 不可用。

$(document).ready(function(){

    var $sidebar   = $("#sidebar"),
    $window    = $(window),
    offset     = $sidebar.offset(),
    topPadding = 15;
    $window.scroll(function() {
        if ($window.scrollTop() > offset.top) {
            $sidebar.addClass('fixed');
        } else {
            $sidebar.removeClass('fixed');
        }
    });
});
var topPadding = 15;
$(window).scroll(function() {
    //alert($(window).scrollTop())
    if ($(window).scrollTop() > $("#sidebar").offset().top) {
        $("#sidebar").addClass('fixed');
    } else {
        $("#sidebar").removeClass('fixed');
    }
});