Adding Animation while switching to dark mode HTML

梦想的初衷 提交于 2020-12-31 14:57:56

问题


I created a dark mode for my webpage by following the link https://dev.to/ananyaneogi/create-a-dark-light-mode-switch-with-css-variables-34l8 I want to add an animation effect so that when the dark mode is applied, the transition is smooth. How do I do it?

I know CSS keyframes are used to add animations or alternatively jQuery can be used, but I can't seem to get how to use them.


回答1:


You could use a css transition. Here follows a simple example, click in the snippet to transition the background color:

const rootDataset = document.documentElement.dataset;

document.onclick = () => {
    const inDarkMode = (rootDataset.theme === 'dark');
    rootDataset.theme = inDarkMode ? '' : 'dark';
}
:root {
    --primary-color: beige;    
}
[data-theme="dark"] {
    --primary-color: grey;    
}
body {
    background: var(--primary-color);
    transition: background 2s;
}


来源:https://stackoverflow.com/questions/61129414/adding-animation-while-switching-to-dark-mode-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!