javascript - css 暗模式变量被故事书忽略

标签 javascript css storybook darkmode

我有以下 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 是否存在我不知道的问题或其他问题?

如果有帮助,这里是将类添加到 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')
  }
})

最佳答案

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

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

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

关于javascript - css 暗模式变量被故事书忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69031931/

相关文章:

javascript - 在悬停状态下突出显示多个元素

javascript - 仅使用 css 的两列复选框布局

html - CSS-下拉菜单重叠

html - 将图像高度调整到容器 div 中而不使其高度增长

reactjs - Storybook react native (IOS) - RangeError : Maximum call stack size exceeded (native stack depth)

javascript - Storybook Actions - 他们到底叫什么?

javascript - 将对象内部的对象数组作为多个对象 JavaScript

javascript - onclick 和 href 都在 anchor 标记中

javascript - Javascript中的Node接口(interface)是一个对象吗?

typescript - Storybook 和 AntDesign 组件 - 如何使用 CRA 和 Typescript 进行设置?