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

如何在JavaScript中用classList.contains判断多个类?

如何判断元素是否包含多个指定CSS类?

问题原因

你尝试的el.classList.contains('section--bg1', 'section--bg2')写法无效,是因为classList.contains()方法仅支持单个类名参数——传入多个参数时,方法只会读取第一个参数,后续参数会被直接忽略,所以无法实现“判断是否包含任意指定类”的需求。

原始代码

// active section
if ( (sectionTop <= replaceItemBottom) && (sectionBottom > replaceItemTop)) {
  // check if current section has bg
  currentSection = el.classList.contains('section--bg1');

  // switch class depending on background image
  if ( currentSection ) { 
    replaceContainer[0].classList.remove('js-replace--reverse');
  } else {
    replaceContainer[0].classList.add('js-replace--reverse')
  }
}

可行解决方案

要判断元素是否包含多个指定类中的任意一个,可以通过多次调用contains()并结合逻辑或运算符||实现,这也是你最终采用的有效方案:

// active section
if ( (sectionTop <= replaceItemBottom) && (sectionBottom > replaceItemTop)) {
  // check if current section has bg
  currentSection = el.classList.contains('section--bg1') || el.classList.contains('section--bg2') || el.classList.contains('section--bg3');

  // switch class depending on background image
  if ( currentSection ) { 
    replaceContainer[0].classList.remove('js-replace--reverse');
  } else {
    replaceContainer[0].classList.add('js-replace--reverse')
  }
}

如果后续需要扩展更多类名,也可以用数组结合Array.some()方法简化代码,提升可维护性:

// active section
if ( (sectionTop <= replaceItemBottom) && (sectionBottom > replaceItemTop)) {
  // 定义需要检查的类名数组
  const targetBgClasses = ['section--bg1', 'section--bg2', 'section--bg3'];
  // 判断元素是否包含数组中任意一个类
  currentSection = targetBgClasses.some(className => el.classList.contains(className));

  // switch class depending on background image
  if ( currentSection ) { 
    replaceContainer[0].classList.remove('js-replace--reverse');
  } else {
    replaceContainer[0].classList.add('js-replace--reverse')
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:05:14