简体   繁体   English

单击时更改字体真棒图标的颜色:CSS / JavaScript

[英]Changing color of Font Awesome icon on click: CSS / JavaScript

Forgive me in advance if I'm being stupid here but I'm trying to change the color of 3 Font Awesome icons from white to black when a menu is clicked on my site using JavaScript to add a class of "active" on top of the current class of "social-icon" so that the CSS is activated.如果我在这里很愚蠢,请提前原谅我,但是当我使用 JavaScript 在我的网站上单击菜单时,我试图将 3 个 Font Awesome 图标的颜色从白色更改为黑色,以在顶部添加“活动”的 class “social-icon”的当前 class 以便激活 CSS。

I'm using a div called 'toggle' as a navbar and currently only the first icon is changed to black when this is clicked.我正在使用一个名为“切换”的 div 作为导航栏,当前只有第一个图标在单击时变为黑色。 I've tried using querySelectorAll instead but that doesn't work and I've also tried moving the social-icon class to within the font awesome icon class but again nothign.我尝试使用 querySelectorAll 来代替,但这不起作用,我还尝试将社交图标 class 移动到字体真棒图标 class 内,但又没有。 I'm just curious at to where I'm going wrong.我只是好奇我哪里出错了。

Thanks谢谢

JS JS

const menuToggle = document.querySelector('.toggle')
const showcase = document.querySelector('.showcase')
const socialToggle = document.querySelector('.social-icon')

menuToggle.addEventListener('click', function() {
    menuToggle.classList.toggle('active')
    showcase.classList.toggle('active')
    socialToggle.classList.toggle('active')
})

CSS CSS

.social {
    position: fixed;
    bottom: 18px;
    right: 40px;
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
}

.social li {
    list-style: none;
}

.social-icon {
    display: inline-block;
    transform: scale(0.5);
    margin-right: 25px;
    transition: 0.5s;
    font-size: 40px;
    cursor: pointer;
}

.social-icon.active {
color: black;
}

HTML HTML


            <div class="toggle"></div>


<ul class="social">
            <li class="social-icon"><i class="fab fa-facebook-f"></i></li>
            <li class="social-icon"><i class="fab fa-instagram"></i></li>
            <li class="social-icon"><i class="fab fa-tiktok"></i></li>
        </ul>

You can use querySelectorAll to get a node list with all the icons and then iterate them:您可以使用querySelectorAll获取包含所有图标的节点列表,然后对其进行迭代:

const menuToggle = document.querySelector('.toggle');
const showcase = document.querySelector('.showcase');
const socialToggle = document.querySelectorAll('.social-icon');

menuToggle.addEventListener('click', function() {
    menuToggle.classList.toggle('active');
    showcase.classList.toggle('active');
    socialToggle.forEach(function(el) {
        el.classList.toggle('active');
    });
})

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

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