GlideJS轮播开启自动播放时触发自定义函数的实现方法
Absolutely, you should leverage GlideJS's built-in event system here—your current approach only handles manual clicks, which is why it doesn't fire during autoplay. Let me break down the fix for you:
The Root of the Problem
Your current code binds handleAnimation exclusively to the click events of .slide__trigger elements. When Glide's autoplay activates, it transitions slides internally without triggering those click events. That's why your function works for manual clicks but not automated transitions.
The Fix: Glide's afterRun Event
GlideJS provides lifecycle events that cover every slide transition scenario (autoplay, manual navigation, keyboard controls, etc.). For your use case, the afterRun event is ideal—it fires after a slide transition completes and the new slide is marked as active.
Here's your updated componentDidMount code:
componentDidMount = () => { const carousel = new Glide(this.myRef.current, { autoplay: 3000, rewind: true, }) // Listen for afterRun to handle all slide activation events carousel.on('afterRun', () => { // Get the currently active slide using the carousel's root ref const activeSlide = this.myRef.current.querySelector('.glide__slide--active'); // Extract the data-step attribute from the active slide const triggerStep = activeSlide.getAttribute('data-step'); // Execute your custom animation function this.handleAnimation(triggerStep); }) carousel.mount() // You can remove the old click event bindings now—afterRun covers manual clicks too! // const myTriggers = document.querySelectorAll(".slide__trigger") // myTriggers.forEach(trigger => { // const triggerStep = trigger.getAttribute("data-step") // trigger.addEventListener("click", () => this.handleAnimation(triggerStep) ) // }) }
Key Notes
- Why
afterRun? It ensures your function runs only when the new slide is fully active, which matches your requirement of triggering after the slide switch completes. If you wanted to fire logic when the transition starts, use therunevent instead. - Ref-Based Querying: Using
this.myRef.currentto find the active slide is more reliable than a globaldocument.querySelector, especially if you have multiple carousels on the page. - Simpler Code: The
afterRunevent handles both autoplay and manual transitions, so you can remove your old click event listeners entirely. This eliminates redundant code and prevents duplicate calls tohandleAnimation.
内容的提问来源于stack exchange,提问作者Mega88

