You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ScrollMagic的setClassToggle添加类后持久保留?

How to Persist a CSS Class After Scrolling Down Past a ScrollMagic Trigger (No Removal on Scroll Up)

Absolutely, this is totally feasible! The default setClassToggle() method is built for toggle behavior—adding the class on scroll down past the trigger, removing it on scroll up—but we can easily adjust ScrollMagic's settings to make the class stick around permanently once added.

Here are two straightforward approaches to achieve this:

1. Disable Scene Reverse (Simplest Method)

ScrollMagic scenes have a reverse option that defaults to true, which tells the scene to "undo" its action when you scroll back up past the trigger. By setting reverse: false, we ensure the class is only added once (on the initial scroll down) and never removed.

// Initialize your ScrollMagic controller first
const controller = new ScrollMagic.Controller();

// Create the scene with reverse disabled
const scene = new ScrollMagic.Scene({
  triggerElement: "#your-trigger-element", // Replace with your trigger selector
  triggerHook: 0.5, // Adjust this to control when the trigger fires (0 = top of viewport, 1 = bottom)
  reverse: false // This is the key line!
})
.setClassToggle("#my-elem", "myclass") // Your original class toggle setup
.addTo(controller);

Why this works:

With reverse: false, the scene only executes its action (adding the class) when you first scroll down past the trigger. When you scroll back up, the scene won't run any reverse logic to remove the class—so it stays on the element indefinitely.

2. Use the onEnter Event Hook

If you prefer more explicit control, you can use the scene's onEnter event to manually add the class. This event only fires when you scroll down into the scene's trigger area, so there's no corresponding event to remove the class on scroll up.

const controller = new ScrollMagic.Controller();

const scene = new ScrollMagic.Scene({
  triggerElement: "#your-trigger-element",
  triggerHook: 0.5
})
.onEnter(function() {
  // Manually add the class when entering the scene
  document.querySelector("#my-elem").classList.add("myclass");
})
.addTo(controller);

Note:

If you want to ensure the class is only added once (even if the user scrolls down past the trigger multiple times), you can add a check to see if the class already exists before adding it:

.onEnter(function() {
  const elem = document.querySelector("#my-elem");
  if (!elem.classList.contains("myclass")) {
    elem.classList.add("myclass");
  }
})

Both methods will give you the behavior you want: the class is added when scrolling down past the trigger and stays on the element forever, even when scrolling back up.

内容的提问来源于stack exchange,提问作者learningtech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:49:43