小编Qua*_*ima的帖子

Vue JS:如何从 vue 组件访问和更改 CSS 根变量以切换 CSS 变量站点主题?

我想在 Vue 组件中访问项目中 css 根变量的值。例如,通过按按钮更改 10 个变量,包括颜色、边距和字体大小,然后按同一按钮将变量更改为其(默认)原始值,实际上是更改值项目中的 css 根变量。我怎样才能做到这一点 ?事实上,我想通过按一个按钮在黑暗和光明之间切换。

这个想法的灵感来自以下链接的更改。链接内的示例是用纯JavaScript脚本编写的,我想在Next Js Framework上开发的Vue项目中使用它。实现一个包含大约 10 个变量的网站,按下按钮以切换暗/亮模式,这些变量的值必须立即更改。

给我启发的 codepen 链接:)

如何访问和更改 CSS 根变量?

new Vue({
	el: "#theme",
	data: {
    return {
      dark: true,
      
    };
  },
  
  watch: {
    dark() {
    
      let bg = this.dark ? "#1b1b1b" : "#f5f5f5";
      let txtColor = this.dark ? "#999999" : "#333333";
      
      document.documentElement.style.setProperty("--bg", bg);
      document.documentElement.style.setProperty("--txt", txtColor);
      
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
:root{

--bg: white;
--txt: black;

}


body {
  background-color: var(--bg);
  color: var(--txt)
}
article {
  padding: 50px
}
article h2 …
Run Code Online (Sandbox Code Playgroud)

javascript css-variables vue.js vue-component nuxt.js

7
推荐指数
1
解决办法
9026
查看次数