梓怡 Dev
梓怡 DevLv1
最近在研究如何实现暗黑主题,并且想要加入一些CSS动画来提升用户体验。我发现,通过使用CSS变量和@media查询,可以很方便地创建和切换不同的主题。特别是利用CSS动画,可以让主题切换更加平滑流畅。

比如,我使用了一个简单的渐变动画来实现从亮色到暗色的过渡。代码如下:

:root {
  --background-color: #ffffff;
  --text-color: #000000;
}

body {
  --background-color: #333333;
  --text-color: #ffffff;
  transition: background-color 0.5s ease, color 0.5s ease;
}

 body {
  background-color: var(--background-color);
  color: var(--text-color);
}


然后,在JavaScript中,可以通过改变data-theme属性来切换主题,并触发相应的CSS动画效果。

function toggleTheme() {
  const theme = document.body.getAttribute('data-theme');
  if (theme === 'dark') {
    document.body.setAttribute('data-theme', 'light');
  } else {
    document.body.setAttribute('data-theme', 'dark');
  }
}


这样,每次点击按钮时,页面就会平滑地切换到另一种主题。我觉得这种做法既美观又实用,大家可以试试看吧!