如何在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
相关产品推荐
相关产品推荐

