基于订阅的变量应用 CSS 属性。深色模式与浅色模式

我想根据用户是否单击了暗模式或亮模式来更改 CSS 属性。每次模式切换时,我都可以获得订阅以捕获值,但我希望能够在单击不同模式时更改 CSS 中的某些属性。

我正在使用角 9

关于如何做到这一点的任何想法?


catspeake
浏览 134回答 3
3回答

宝慕林4294392

您可以使用BehaviourSubject RXJS 来实现此功能。默认情况下,当用户使用 next() 方法单击开关时,您可以设置为 false 并使用亮模式,将行为主题更改为 true 然后变暗等。您必须在 init 上订阅 BehaviourSubject 变量并处理响应。您可以在BehaviourSubject获得参考。我个人在我的项目中实现了这个黑暗模式功能,这里是链接telivic.com我在该网站中使用的方法如下。希望这对你有用。addDark(){    document.getElementById('nav').classList.add('dark');    document.getElementById('box').style.backgroundColor = "#35363A";     document.getElementsByTagName("BODY")[0].classList.add('dark');     document.getElementById('modal').style.backgroundColor ="bisque";     if(this.service.flag){      document.getElementById('opt').classList.add('dark');     }     document.getElementById('gen').style.color="white";       }  removeDark(){    document.getElementById('nav').classList.remove('dark');    document.getElementById('box').style.backgroundColor = "#fff";     document.getElementsByTagName("BODY")[0].classList.remove('dark');     document.getElementById('modal').style.backgroundColor ="white";     if(this.service.flag){      document.getElementById('opt').classList.remove('dark');     }     document.getElementById('gen').style.color="black";  }  /*Binded my switch to this function I have used service so that user   dark/light mode preference can be processed in other pages also.*/  darkMode(){    this.dark = !this.dark;    this.userService.setMode();    if(this.dark){      this.addDark();    }else{     this.removeDark();          }      }

一只萌萌小番薯

您可以使用样式组件。一个例子是:import styled from 'styled-components'const ComponentName = styled.div`&nbsp; &nbsp; color: ${props => props.mode === `dark` ? `white` : `black`};`然后在你的渲染中,这样做:<ComponentName mode={mode} />

白衣非少年

你可以在ts文件中添加一个变量,modeType: string;这将根据用户的选择更改为“深色”或“浅色”。在您的 html 中更改 css 属性使用 ngClass。或者使用<div class="{{modeType == 'dark' ? 'dark-property': 'light-property'}}">在你的 CSS 文件中,.dark-property{&nbsp;add your "dark" css styles}.light-property{&nbsp;add your "light" css styles}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript