在 Javascript 函数中使用 classList 添加 CSS 类,但样式发生冲突,因为最新的类不优先
P粉738821035
P粉738821035 2023-09-10 17:10:38
0
2
494

我的函数计算屏幕上可见的卡片数量,如果全部显示,则将 arrow-up 类添加到我的图标中,如果某些卡片仍然对用户隐藏,则 arrow添加-down图标。

const showMoreIcon = document.querySelector('.cta-icon');

function myFunction(){
   const btnIcon = cardsOnShow >= cards.length ? 'arrow-up' : 'arrow-down';
   showMoreIcon.classList.add(btnIcon);
}
<span class="medium-icon"></span>

这有效,但是我可以在 DOM 中看到正确的类被添加到 span 中,因为我期望它,因为添加了 arrow-down 类首先(在显示所有可见卡片之前,用户必须多次展开内容) - 然后,尽管添加了 arrow-up 类,但它不会覆盖 arrow-down。 p>

如何确保添加 arrow-up 时,arrow-down 被删除,反之亦然?我之前曾使用 toggle 来实现简单的打开/关闭图标,但这不起作用,因为它在关闭之前可能会展开多次。

P粉738821035
P粉738821035

全部回复(2)
P粉579008412

我建议删除您不再需要的课程:

function myFunction(){
   if (cardsOnShow >= cards.length) {
      showMoreIcon.classList.add('arrow-up')
      showMoreIcon.classList.remove('arrow-down')
   } else {
      showMoreIcon.classList.remove('arrow-up')
      showMoreIcon.classList.add('arrow-down')
   }
}

P粉395056196

级联考虑了许多因素 a>,这是一组规则,用于确定当两个冲突的规则应用于同一元素时哪个规则“获胜”。

在 HTML 元素上定义类的顺序不是这些因素之一。

就级联而言是相同的。

删除不应应用的类。

if (cardsOnShow >= cards.length) {
    showMoreIcon.classList.add("arrow-up");
    showMoreIcon.classList.remove("arrow-down");
} else {
    showMoreIcon.classList.add("arrow-down");
    showMoreIcon.classList.remove("arrow-up");
}

或者以只关心单个类来改变方向的方式编写 CSS:

.arrow {
    /* arrow up CSS */
}
.arrow.invert {
    /* override the up rule and replace with the down rule
}

然后

if (cardsOnShow >= cards.length) {
    showMoreIcon.classList.remove("invert");
} else {
    showMoreIcon.classList.add("invert");
}

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!