手写JS滑块时classList报undefined读取错误解决方案
报错原因
触发Uncaught TypeError: Cannot read properties of undefined (reading 'classList')的核心原因是数组索引越界。
当前页面一共只有2个类名为slid的元素,存入数组后有效索引范围是0和1。当激活状态在第二个滑块(对应索引1)时,执行numberArray++后得到的索引值为2,slid[2]不存在,值为undefined,自然无法读取其classList属性。
你测试时console.log(slid[numberArray].classList)能正常输出,是因为当时激活的是第一个滑块(索引0),自增后得到索引1,对应元素真实存在,所以打印正常;切到第二个滑块再点右箭头就会触发报错。
自主实现提示
你可以基于现有结构自行补全逻辑,无需大改:
- 右箭头切换时,索引自增后增加边界判断:如果计算后的索引大于等于
slid.length,将索引重置为0,即可实现首尾循环轮播 - 左箭头切换做反向处理:索引自减后如果值小于0,将索引设置为
slid.length - 1,跳回最后一个滑块 - 当前逻辑每次点击都要遍历整个
slid数组查找带active类的元素,后续优化可以单独存一个变量记录当前激活索引,减少不必要的遍历,不做这步优化也不影响基础功能运行
现有完整代码备份
JavaScript 逻辑
const slid = [...document.querySelectorAll('.slid')]; const arrows = document.querySelectorAll('.arrows-slider .arrow'); slid.forEach(s => { if( s.classList.contains('active') == false){ s.style.opacity = '0'; } }); arrows.forEach( arrow =>{ arrow.addEventListener('click', function(){ if(this.classList.contains('arrows-right')){ slid.forEach(s => { if( s.classList.contains('active')){ s.classList.remove('active'); let numberArray = slid.indexOf(s); numberArray ++; slid[numberArray].classList.add('active'); console.log(slid[numberArray].classList); } }); }else if( this.classList.contains('arrows-left')){ } }); });
CSS 样式
.slider { position: absolute; top: 0; left: 0; width: 100%; background-image: url('../img/mirrored_squares.png'); height: 100vh; } .slid { position: absolute; width: 100%; height: 100vh; opacity: 0; } .active { opacity: 1 !important; } .img-slid { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 35%; height: 50%; background-size: cover; } .engine { background-image: url("../img/silnik.jpg"); } .exhaust { background-image: url("../img/wydech.jpg"); } .slid-text { position: absolute; top: 50%; left: 11%; transform: translateY(-50%); font-size: 8rem; text-transform: uppercase; color: #fff; font-family: 'Black Ops One', cursive; } .number-slaid { position: absolute; bottom: 8%; right: 8%; font-size: 2rem; color: #fff; font-family: 'Black Ops One', cursive; } .arrows-left { position: absolute; top: 50%; left: 5%; transform: translateY(-50%) rotate(45deg); } .arrows-right { position: absolute; top: 50%; right: 5%; transform: translateY(-50%) rotate(-135deg); } .arrow { width: 80px; height: 80px; border-left: 2px solid #000; border-bottom: 2px solid #000; cursor: pointer; }
HTML 结构
<section class="slider"> <div class="slid slid1 active"> <div class="engine img-slid"> </div> <p class="slid-text">engine</p> <p class="number-slaid">01</p> </div> <div class="slid slid2 "> <div class="exhaust img-slid"></div> <p class="slid-text">exhaust</p> <p class="number-slaid">02</p> </div> <div class="arrows-slider"> <div class="arrows-left arrow"></div> <div class="arrows-right arrow"></div> </div> </section>
内容的提问来源于stack exchange,提问作者karamba
相关产品推荐
相关产品推荐

