You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery平滑滚动失效:无法读取undefined的'top'属性

Hey there! I know you've spent hours troubleshooting this smooth scroll issue—let's break down what might be going wrong with your code and fix it up.

Common Fixes for Your jQuery Smooth Scroll

First, let's go through the most likely culprits:

1. jQuery Loading Order is Wrong

Looking at your code snippet, it seems like your custom scroll script might be running before jQuery finishes loading. If that's the case, you'll see a $ is not defined error in your browser's console.

Fix this by moving your custom script after the jQuery import:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() { 
  var scrollLink = $('.option-name'); 
  scrollLink.click(function(e){ 
    e.preventDefault(); 
    let linkRef = $(this).attr('href'); 
    let position = $(linkRef).offset().top; 
    $('html, body').animate({ scrollTop : position }, 500) 
  }) 
}); 
</script>

2. Target Element Doesn't Exist (or ID Mismatch)

Double-check that the href value of your .option-name links (like #about-section) matches the id of the element you're trying to scroll to exactly—IDs are case-sensitive! If the target element doesn't exist, $(linkRef).offset().top will return undefined, and the animation won't run at all.

3. Prevent Animation Queue Build-Up

If users click your scroll links quickly multiple times, the animations will stack up and cause janky scrolling. Add .stop(true, true) to clear the animation queue and jump to the end of any ongoing animation:

$('html, body').stop(true, true).animate({ scrollTop : position }, 500);

4. CSS Overflow Settings Are Interfering

Check if your body or any parent container has overflow: hidden or overflow-y: scroll set. These styles can break the calculation of scrollTop and prevent smooth scrolling from working as expected. Adjust those styles if needed.

Bonus: Native Smooth Scroll (No jQuery Needed)

If you don't need to support super old browsers, you can ditch jQuery entirely for a simpler solution. Add this CSS:

html {
  scroll-behavior: smooth;
}

Then just make sure your links point to valid element IDs—no extra JS required! This is great for basic smooth scroll needs, though jQuery gives you more control over animation timing and custom behavior.

One last pro tip: Open your browser's dev tools (F12) and check the Console tab for errors. Syntax issues, missing elements, or undefined variables will show up here and point you straight to the problem.

内容的提问来源于stack exchange,提问作者ISAAC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:54:12