简体   繁体   English

在 Bootstrap 4.6 手风琴上更改图标

[英]Change Icon on Bootstrap 4.6 accordion

I want to have a 'plus' icon when the accordion is collapsed, and a 'minus' icon when the accordion is 'expanded'.我想在折叠手风琴时有一个“加号”图标,当手风琴“展开”时有一个“减号”图标。 I have checked other answers on the internet, but what am I asking is can't I do something simple like this?我已经检查了互联网上的其他答案,但我要问的是我不能做这样简单的事情吗? (For learning purposes) (用于学习目的)

Say I place both the plus and minus icons on the accordion <i class="fa-plus"> <i class="fa-minus"> As I see, when the accordion is collapsed, it has a collapsed class, so I'd like to hide and show both the icons as the collapsed class gets toggled on click.假设我在手风琴上放置了加号和减号图标<i class="fa-plus"> <i class="fa-minus">如我所见,当手风琴折叠时,它有collapsed的 class,所以我'想要隐藏和显示两个图标,因为collapsed的 class 在点击时被切换。 Why doesn't it work as the DOM gets updated when the accordion is clicked?为什么当点击手风琴时 DOM 更新时它不起作用?

 if(document.getElementById('candidateName').classList.contains('collapsed')) { document.querySelector('.fa-minus').style.display = 'none'; document.querySelector('.fa-plus').style.display = 'block'; } else { document.querySelector('.fa-plus').style.display = 'none'; document.querySelector('.fa-minus').style.display = 'block'; }

Please note that this is just for learning purposes.请注意,这仅用于学习目的。 I want to understand this, please don't get offended.我想明白这一点,请不要生气。 Thankyou谢谢

Glad you are learning.很高兴你正在学习。 Apologies if my response comes across in a different plane than your current level.如果我的回答与您当前的水平不同,请道歉。

When you run JS, you're executing the code in the current state of the content.当你运行 JS 时,你是在执行当前 state 中的代码内容。 It appears that you are hoping for the icon to change from a + to a - and vice verse when the accordion is expanded/collapsed.当手风琴展开/折叠时,您似乎希望图标从+变为- ,反之亦然。

What you need to do, is watch the page for changes to the accordion - these are called event listeners.您需要做的是观察页面以了解手风琴的变化——这些被称为事件监听器。 Bootstrap has some really convenient ones that you can use for this. Bootstrap 有一些非常方便的工具,您可以使用它们。 Since the Accordion uses collapse events API.由于 Accordion 使用 折叠事件API。 From there, you can watch the page for changes, and execute the change you want whenever that change happens.从那里,您可以查看页面的更改,并在更改发生时执行您想要的更改。

const myCollapsible = document.getElementById('myCollapsible')
myCollapsible.addEventListener('hidden.bs.collapse', event => {
  // do something...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM