JavaScript图片轮播教程报错:TypeError: slides is null
Fixing Your "TypeError: slides is null" Carousel Issue
Hey there, no need to feel stuck—tiny syntax typos are the bane of every developer’s existence, especially when you’re starting out with JavaScript! Let’s break down why your carousel isn’t working and fix it right away.
The Two Key Issues Causing Your Problem
- JavaScript Attribute Selector Mistake: When you tried to grab the slides container, you used
querySelector("data-slides")—this is invalid becausedata-slidesis a custom data attribute, so you need to wrap it in square brackets to use the attribute selector:querySelector("[data-slides]"). Without the brackets, the browser is looking for a<data-slides>HTML element (which doesn’t exist), henceslidesbeingnull. - CSS Class Name Typo: In your CSS, you wrote
.carouseslinstead of.carousel—this misspelling meant none of your carousel container styles were being applied, so even if the JS worked, the visual behavior would be off.
Corrected Code
Fixed JavaScript
const buttons = document.querySelectorAll("[data-carousel-button]") buttons.forEach(button => { button.addEventListener("click", () => { const offset = button.dataset.carouselButton === "next" ? 1 : -1 const slides = button .closest("[data-carousel]") .querySelector("[data-slides]") // Fixed attribute selector here const activeSlide = slides.querySelector("[data-active]") let newIndex = [...slides.children].indexOf(activeSlide) + offset if (newIndex < 0) newIndex = slides.children.length - 1 if (newIndex >= slides.children.length) newIndex = 0 slides.children[newIndex].dataset.active = true delete activeSlide.dataset.active }) })
Fixed CSS
*::before, *::after { padding:0; margin:0; box-sizing: border-box; } .carousel { /* Fixed class name spelling here */ width: 100vw; height: 100vh; position: relative; } .slide { position: absolute; inset: 0; opacity: 0; } .slide > img { display: block; width: 100%; height: 100%; object-fit:cover; object-position: center; } .slide[data-active] { opacity:1; } .carousel-button { position: absolute; background: none; border: none; font-size: 4rem; top: 50%; transform: translateY(-50%); z-index: 2; color: rgba(255, 255, 255, .5); cursor: pointer; border-radius: .25rem; padding: 0.5rem; background-color: rgba(0, 0, 0, .1); } .carousel-button:hover, .carousel-button:focus { color: white; background-color: rgba(0, 0, 0, .2); } .carousel-button.next { left: 1rem; } .carousel-button.prev { right: 1rem; }
Your HTML code is already correct, so no changes needed there!
Once you update these two parts, your carousel should work exactly like the tutorial version. Remember to always double-check selectors and class names—small typos can cause big headaches, but they’re easy fixes once you spot them.
内容的提问来源于stack exchange,提问作者joob
相关产品推荐
相关产品推荐

