JS为js-scroll类元素实现滚动动画无响应问题排查
问题原因及修复方案
你代码中存在3个致命错误导致效果不生效,按优先级排序如下:
- CSS优先级冲突
你通过JS直接给.js-scroll元素设置了style.opacity = "0"的行内样式,行内样式优先级远高于类选择器.scrolled-proj,哪怕类成功添加,也无法覆盖行内的透明度设置,这是你修改in_view固定返回true仍看不到效果的核心原因。 - 变量未定义报错
in_view函数的形参命名为off,但函数内部判断时用的是未定义的变量offset,代码执行到此处会直接抛出ReferenceError,导致后续逻辑全部中断,滚动事件触发的回调直接执行失败。 - CSS高度语法错误
.projects选择器中height: 5*var(--height)的写法不符合CSS语法,数值运算必须包裹在calc()中,该错误会导致容器高度不生效,可能出现页面无法滚动的问题。
修复代码
1. JS修改
const scroll_elem = document.querySelectorAll(".js-scroll"); // 统一变量名 const in_view = (el, offset) => { const top = el.getBoundingClientRect().top; return ( top <= (window.innerHeight - offset) ); } const scroll_animation = () => { scroll_elem.forEach((el) => { if(in_view(el, 100)){ el.classList.add("scrolled-proj"); }else{ el.classList.remove("scrolled-proj"); } }) } window.addEventListener("scroll", scroll_animation); // 页面加载完成直接执行一次,显示首屏元素 window.addEventListener("load", scroll_animation);
2. CSS修改
/* 新增.js-scroll默认透明度,和.scrolled-proj优先级相同,后定义的会覆盖 */ .js-scroll{ opacity: 0; /* 可选加过渡动画,效果更流畅 */ transition: opacity 0.3s ease; } .project-elem { background-color: greenyellow; margin: 5rem 5rem; --height: 300px; } .projects { margin: 0; padding: 3rem; background-color: #DDCDE8; font: Asap, sans-serif; /* 运算用calc包裹 */ height: calc(5 * var(--height)); text-align: center; } .project-n { background-color: green; text-align: center; width: 60%; height: 250px; float: left; padding: 3rem; box-sizing: border-box; } .img { background-color: blue; text-align: center; margin-left: 40%; height: 250px; } .scrolled-proj{ opacity: 1; }
3. HTML修正(可选,不影响功能)
把<div class="projects" id=#projects>改为<div class="projects" id="projects">,移除id属性中多余的#号。
内容的提问来源于stack exchange,提问作者rjc810
相关产品推荐
相关产品推荐

