如何像 GitHub 一样切换到 Chromes 深色滚动条?

Mar*_*ndt 7 html javascript google-chrome darkmode

我刚刚发现,当您使用 GitHub 的暗模式时,GitHub 在 Chrome 中使用暗滚动条。如果您切换颜色模式,滚动条也会切换。

我怎样才能达到这种行为?我找不到任何方法告诉浏览器使用暗模式。

暗模式滚动条:

暗模式滚动条

Cal*_*lor 12

这是 CSS 属性color-scheme。这还将在表单控件、背景颜色和文本颜色上应用主题。

目前支持 Chrome 81 和 Safari 13

MDN 来源:https : //developer.mozilla.org/en-US/docs/Web/CSS/color-scheme

:root {
  color-scheme: dark;
}

.container {
  padding: 25px;
  height: 2000px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="text">Dark Mode</div>
  <input type="text" placeholder="input with dark theme"/>
</div>
Run Code Online (Sandbox Code Playgroud)

如果您想即时更改主题,则会遇到滚动条在交互之前不会更新其配色方案的问题。刷新滚动条的一种方法是更改​​其父溢出属性,在本例中为html元素。

const btn = document.querySelector("button");
let isDark = true;

btn.addEventListener("click", () => {
  // remove scrollbars
  document.documentElement.style.overflow = "hidden";
  // trigger reflow so that overflow style is applied
  document.body.clientWidth;
  // change scheme
  document.documentElement.setAttribute(
    "data-color-scheme",
    isDark ? "light" : "dark"
  );
  // remove overflow style, which will bring back the scrollbar with the correct scheme 
  document.documentElement.style.overflow = "";

  isDark = !isDark;
});
Run Code Online (Sandbox Code Playgroud)
[data-color-scheme="dark"] {
  color-scheme: dark;
}

[data-color-scheme="light"] {
  color-scheme: light;
}

.container {
  padding: 25px;
  height: 2000px;
 }
Run Code Online (Sandbox Code Playgroud)
<html lang="en" data-color-scheme="dark">
<body>
  <div class="container">
    <button>Click to Change Color Scheme</button>
    <br>
    <br>
    <br>
    <input type="text" placeholder="dummy input">
  </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)