3 回答

TA貢獻2021條經驗 獲得超8個贊
您可以使用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();
}
}

TA貢獻1795條經驗 獲得超7個贊
您可以使用樣式組件。一個例子是:
import styled from 'styled-components'
const ComponentName = styled.div`
color: ${props => props.mode === `dark` ? `white` : `black`};
`
然后在你的渲染中,這樣做:
<ComponentName mode={mode} />

TA貢獻1155條經驗 獲得超0個贊
你可以在ts文件中添加一個變量,
modeType: string;
這將根據用戶的選擇更改為“深色”或“淺色”。
在您的 html 中更改 css 屬性使用 ngClass?;蛘呤褂?/p>
<div class="{{modeType == 'dark' ? 'dark-property': 'light-property'}}">
在你的 CSS 文件中,
.dark-property{
add your "dark" css styles
}
.light-property{
add your "light" css styles
}
添加回答
舉報