求助:Cannot read property 'top' of undefined错误排查(附jQuery代码)
Hey there, let's break down why you're hitting this error and how to fix it.
The Root Cause
This error pops up because your scroll event handler might run before the window.load callback finishes executing. At that point, offset1 hasn't been assigned a value yet—it's still undefined, so trying to access offset1.top throws the error.
Another possible culprit: if the element #scroller-wrap1 doesn't exist in your DOM, $holder1.offset() will also return undefined, leading to the same problem.
Solution 1: Guard Against Undefined in the Scroll Handler
Add a quick check to make sure offset1 is set before trying to use it. This prevents the error even if the scroll event fires early:
var $ = jQuery; var $window = $(window), $moving1 = $(".scroller1"), $holder1 = $("#scroller-wrap1"), offset1; $window.load(function() { // First, verify the holder element exists if ($holder1.length === 0) { console.error("Warning: Element #scroller-wrap1 not found!"); return; } offset1 = $holder1.offset(); }); $window.scroll(function() { // Exit early if offset1 isn't ready yet if (!offset1) return; if ($window.scrollTop() > offset1.top) { $moving1.addClass('fixed'); } else { $moving1.removeClass('fixed'); } if ($window.scrollTop() > (offset1.top + $holder1.height() - $moving1.height() - 60)) { // Your existing code here } });
Solution 2: Bind the Scroll Handler After Initializing Offset
A more reliable approach is to only attach the scroll event after offset1 has been set. This guarantees the value exists when the handler runs:
var $ = jQuery; var $window = $(window), $moving1 = $(".scroller1"), $holder1 = $("#scroller-wrap1"), offset1; $window.load(function() { if ($holder1.length === 0) { console.error("Warning: Element #scroller-wrap1 not found!"); return; } offset1 = $holder1.offset(); // Now bind the scroll handler $window.scroll(function() { if ($window.scrollTop() > offset1.top) { $moving1.addClass('fixed'); } else { $moving1.removeClass('fixed'); } if ($window.scrollTop() > (offset1.top + $holder1.height() - $moving1.height() - 60)) { // Your existing code here } }); // Trigger scroll once to set the initial state correctly $window.trigger('scroll'); });
Bonus: Use $(document).ready() If Possible
If your layout doesn't depend on images or external resources loading (i.e., #scroller-wrap1's position is set via CSS without waiting for assets), you can replace $window.load() with $(document).ready(). This runs earlier, so your scroll logic will be ready sooner:
$(document).ready(function() { // Same initialization code here });
内容的提问来源于stack exchange,提问作者FilipeOS

