css 故事书忽略暗模式变量

css darkmode variables being ignored by storybook

我有以下 css 已加载到我的项目中:

// Default theme (light mode)
:root {
  /* Typography */
  --col-body-text: #0b0c0c;
  --col-body-text-light: #505a5f;
}

// Dark mode theme
:root.dark {
  /* Typography */
  --col-body-text: #c5c5c5;
  --col-body-text-light: #f8f8f8;
}

在我的实际应用中,这按预期工作,但是,在故事书中,它忽略了暗模式变量。

我已经更新了我的 preview.js 文件以在选择暗模式时将“.dark”添加到 `HTML 元素 - 这按预期工作 - 实际上所有其他暗模式特定代码在组件中工作正常。只有那些变量被忽略了。

在我不知道的故事书中使用 :root 是否存在问题?

如果有帮助,这里是将 class 添加到 HTML 元素的代码:


// get an instance to the communication channel for the manager and preview
const channel = addons.getChannel()

// switch body class for story along with interface theme
channel.on('DARK_MODE', isDark => {
  if (isDark) {
    document.documentElement.classList.add('dark')
  } else {
    document.documentElement.classList.remove('dark')
  }
})

尝试
CSS -> body.dark {
而不是 :root.dark {

channel.on('DARK_MODE', isDark => document.body.classList.toggle('dark', isDark))

如果您将此类样式表放置在 HTML 页面中(例如在 <head> 中),则 :root 选择器会引用 <html> (https://developer.mozilla.org/en-US/docs/Web/CSS/:root) .如果你想将 :root 选择器与 class 一起使用,你需要在 <html> 元素上设置 class(而不是另一个建议的 <body>答案),所以 document.documentElement.classList.add('dark') 是正确的。

有一个使用 Storybook 语法和功能的游乐场,我在其中为您创建了一个工作示例:https://webcomponents.dev/edit/p8TI3583HotsFNWjBMd8/src/index.stories.js

不确定您的 Storybook 是否以其他方式配置,也许您的样式表并未真正添加或稍后在某处被覆盖。还请验证您是否正确使用 CSS 自定义属性(又名 CSS vars),我希望工作演示也能帮助您。