使用jQuery实现粘性导航栏遇‘$’及document未定义错误求助
Hey there! Let's walk through why you're hitting these two errors and how to get your sticky navigation working properly.
1. Why '$' is not defined happens (and how to fix it)
This error means your browser or ESLint doesn't recognize the jQuery $ shorthand—usually because jQuery itself hasn't been loaded before your custom code, or it's not loaded at all.
Here's how to fix it:
- Load jQuery before your script: Always put the jQuery library import above your custom JavaScript. For example, using a CDN:
<!-- First, load jQuery --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <!-- Then your sticky nav code --> <script> $(document).ready(function() { // Your sticky nav logic here const nav = $('nav'); $(window).scroll(function() { if ($(this).scrollTop() > 50) { nav.addClass('sticky'); } else { nav.removeClass('sticky'); } }); }); </script> - If using a module bundler (Webpack/Vite): You need to explicitly import jQuery and assign it to
$:import $ from 'jquery'; $(document).ready(function() { // Sticky nav code here }); - ESLint-specific fix: If ESLint is flagging
$even after loading jQuery, add a comment at the top of your script to tell ESLint it's a global variable:
Or update your ESLint config (e.g.,/* global $ */ $(document).ready(function() { // Your code });.eslintrc.json) to include jQuery:{ "globals": { "$": true } }
2. Why 'document' is not defined happens (and how to fix it)
This is almost always an ESLint configuration issue. ESLint checks for defined variables, and if it's set to a non-browser environment (like Node.js), it won't recognize browser globals like document.
Fixes:
- Update ESLint env settings: In your
.eslintrc.json(or similar config file), add thebrowserenvironment to let ESLint know you're working in a browser context:{ "env": { "browser": true, "es2021": true } } - Add a global comment: If you don't want to tweak the config, add this comment at the top of your script:
/* global document */
Quick Working Example
Here's a full, minimal example that should work without errors:
<!DOCTYPE html> <html> <head> <style> nav { padding: 1rem; background: #333; color: white; position: relative; top: 0; transition: top 0.3s; } .sticky { position: fixed; top: 0; width: 100%; } .content { height: 2000px; /* Just to make scrolling possible */ } </style> </head> <body> <nav id="main-nav">Sticky Nav</nav> <div class="content">Scroll down to see the nav stick!</div> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> /* global $, document */ $(document).ready(function() { const $nav = $('#main-nav'); const navTop = $nav.offset().top; $(window).scroll(function() { if ($(window).scrollTop() > navTop) { $nav.addClass('sticky'); } else { $nav.removeClass('sticky'); } }); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Jafar
相关产品推荐
相关产品推荐

