为何我的JavaScript视差效果失效?导航栏无法固定顶部
嘿,别慌!作为刚接触HTML5、CSS3和JavaScript的新手,遇到JS代码不生效的问题太正常啦,我来帮你一步步排查解决~
一、先补全你的JavaScript代码
你贴出来的JS代码是不完整的,最后一行window.mozRequestAn...明显被截断了,这会直接导致功能失效。原示例的完整核心代码应该包含完整的requestAnimFrame兼容写法,以及实现视差和导航固定的Scroller函数,我帮你补全了:
$(document).ready(function() { var $content = $('header .content'), $blur = $('header .overlay'), wHeight = $(window).height(); $(window).on('resize', function() { wHeight = $(window).height(); }); // 完整的requestAnimFrame兼容代码 window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); // 实现滚动监听的核心函数 function Scroller() { this.latestKnownScrollY = 0; this.ticking = false; } Scroller.prototype = { init: function() { window.addEventListener('scroll', this.onScroll.bind(this), false); this.update(); }, onScroll: function() { this.latestKnownScrollY = window.scrollY; this.requestTick(); }, requestTick: function() { if(!this.ticking) { window.requestAnimFrame(this.update.bind(this)); this.ticking = true; } }, update: function() { var currentScrollY = this.latestKnownScrollY; this.ticking = false; // 视差滚动效果逻辑 var slowScroll = currentScrollY / 2; var blurScroll = currentScrollY * 2; var headerHeight = $('header').outerHeight(); $content.css({ 'transform': 'translateY(' + slowScroll + 'px)' }); $blur.css({ 'opacity': blurScroll / wHeight }); // 导航栏固定核心逻辑:滚动超过header高度时添加固定类 if(currentScrollY > headerHeight) { $('nav').addClass('fixed'); } else { $('nav').removeClass('fixed'); } } }; var scroller = new Scroller(); scroller.init(); });
二、必须引入jQuery库
原示例用到了$(jQuery语法),但你没提到是否在页面里引入了jQuery!如果没引入,所有依赖jQuery的代码都会完全不工作。你需要在自定义JS代码之前引入jQuery:
<!-- 可以用在线CDN,也可以下载本地文件引入 --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
三、检查导航栏的CSS固定样式
光有JS还不够,你得给导航栏写好固定状态的CSS样式,不然JS添加fixed类也看不到效果:
/* 导航栏默认样式 */ nav { position: relative; width: 100%; padding: 1rem; transition: all 0.3s ease; } /* 滚动到顶部后的固定样式 */ nav.fixed { position: fixed; top: 0; left: 0; z-index: 999; /* 加个背景色避免内容透过导航栏显示 */ background-color: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
四、排查Dreamweaver的预览问题
有时候Dreamweaver的本地预览会有缓存或者路径问题,你可以试试:
- 直接用浏览器打开本地HTML文件,而不是通过Dreamweaver的预览按钮;
- 清空浏览器缓存后再刷新页面;
- 检查外部JS/CSS的相对路径是否正确,比如你把JS文件放在
js/文件夹,就要写src="js/your-script.js",别写错路径导致文件没加载。
内容的提问来源于stack exchange,提问作者Henk Nortje
相关产品推荐
相关产品推荐

