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

滚动时为元素组逐个添加类并反向操作(首个元素类保留)

实现滚动时逐个添加/移除类(首个元素始终保留类)

我来帮你完善这个滚动动画的功能,实现**向下滚动时逐个给.list-tile添加animate-up类,向上滚动时逐个移除(但第一个元素永远保留该类)**的效果。

核心逻辑梳理

  • 用索引跟踪当前最后一个激活的元素,向下滚动时递增索引并给对应元素加类
  • 向上滚动时递减索引(但不小于0),移除对应元素的类,确保第一个元素始终保留激活类
  • 修复原代码中元素选择、滚动方向判断的问题,避免重复操作类名

完整代码实现

HTML结构

<div class="hero-list">
  <div class="hero-list-container">
    <div class="list-tile animate-up"> <!-- 首个元素默认激活 -->
      <div class="module-background" style="background-image: url(https://picsum.photos/id/1015/1920/1080)"></div>
    </div>
    <div class="list-tile">
      <div class="module-background" style="background-image: url(https://picsum.photos/id/1016/1920/1080)"></div>
    </div>
    <div class="list-tile">
      <div class="module-background" style="background-image: url(https://picsum.photos/id/1018/1920/1080)"></div>
    </div>
    <div class="list-tile">
      <div class="module-background" style="background-image: url(https://picsum.photos/id/1019/1920/1080)"></div>
    </div>
  </div>
</div>

CSS样式

.hero-list {
  height: 100vh;
  width: 100%;
  touch-action: pan-x;
  user-select: none;
  -webkit-user-drag: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  position: relative;
  overflow: hidden;
}

.hero-list .hero-list-container {
  position: relative;
  z-index: 901;
  height: 100vh;
  overflow: hidden;
}

.hero-list .hero-list-container .list-tile {
  width: 100%;
  height: 100vh;
  margin: 0 auto;
  position: absolute;
  top: 0;
  left: 0;
  box-sizing: border-box;
  overflow: hidden;
  transform: translate3d(0, 100%, 0);
  transition-duration: 1s;
  transition-property: transform;
  transition-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
}

.hero-list .hero-list-container .list-tile:nth-of-type(2) {
  background-color: green;
}

.hero-list .hero-list-container .list-tile:nth-of-type(3) {
  background-color: blue;
}

.hero-list .hero-list-container .list-tile .module-background {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  transform: translate3d(0, -20%, 0) scale(1.5);
  transition: transform 1s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.hero-list .hero-list-container .list-tile.animate-up {
  transform: translate3d(0, 0%, 0);
}

.hero-list .hero-list-container .list-tile.animate-up .module-background {
  transform: translate3d(0, 0%, 0) scale(1);
}

JavaScript逻辑(整合滚动方向插件)

// 滚动方向检测插件
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});

// 核心滚动逻辑
$(document).ready(function() {
  const tiles = $('.list-tile');
  let currentIndex = 0; // 跟踪最后一个激活的元素索引
  const totalTiles = tiles.length;

  $(window).mousewheel(function(event, delta) {
    if (delta < 0) {
      // 向下滚动:激活下一个元素(如果还有未激活的)
      if (currentIndex < totalTiles - 1) {
        currentIndex++;
        $(tiles[currentIndex]).addClass('animate-up');
      }
    } else {
      // 向上滚动:取消上一个元素的激活(第一个元素永远保留)
      if (currentIndex > 0) {
        $(tiles[currentIndex]).removeClass('animate-up');
        currentIndex--;
      }
    }
  });

  // 强制首个元素始终激活
  $(tiles[0]).addClass('animate-up');
});

功能亮点说明

  • 精准滚动控制:通过delta值准确区分上下滚动,避免误触发
  • 索引安全边界:限制索引范围在0到总元素数-1之间,防止越界操作
  • 首个元素保护:初始化时强制激活第一个元素,向上滚动时不会移除它的激活类
  • 动画平滑性:移除CSS中不必要的!important,保证过渡动画自然流畅

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:02:18