简体   繁体   中英

How to switch between 2 icons?

I'm working on a Hugo theme for my site and this theme have the ability to switch from light to a dark mode. I want to change the icon when the theme is in light when the dark mode is activated.

This is the javascipt part of the code:

_Blog.toggleTheme = function() {
        const currentTheme = window.localStorage && window.localStorage.getItem('theme')
        const isDark = currentTheme === 'dark'
        $('body').toggleClass('dark-theme', isDark)
        $('.theme-switch').on('click', () => {
            $('body').toggleClass('dark-theme')
            window.localStorage &&
                window.localStorage.setItem('theme', document.body.classList.contains('dark-theme') ? 'dark' : 'light', )
        })
    }

and this is the HTML part:

<a href="javascript:void(0);" class="theme-switch"><i class="iconfont icon-sun"></i></a>&nbsp;

What I'm trying to resolve is that when I click on the icon, it changes to another icon. So "icon-sun" on click can become "icon-moon".

You could just add the .toggle() jQuery method to your function or to a seperate click event: $('.icon-sun, .icon-moon').toggle(); In this case, you will be toggling their visibility. For a smoother toggle you could also use .fadeToggle() .

This scripts will do it. add this to one of your script tags. Change icon-facebook to the icon that you want. because i dont think the theme you are working on has icon-moon. if you want to I can show you how to add extra set of icons to the theme.

$('.theme-switch').click(function(){
$(this).find("i").toggleClass("icon-sun").toggleClass("icon-facebook");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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