728x90
반응형
테마 변경 - 데이터 속성
data-* 속성은 다른 조작을 하지 않고도, HTML 요소에 추가 정보를 저장할 수 있게 도와줍니다. 해당 속성은 아래와 같이 접근할 수 있습니다.
//Javascript 접근
document.documentElement.setAttribute('data-theme', 'light');
document.documentElement.getAttribute('data-theme');
const body = document.querySelector("body");
body.dataset.theme;
//만약 data-theme-switch "-"는 자동으로 camel-case 변환
body.dataset.themeSwitch;
스위치 변경 시 마다 document data-theme 속성을 light/dark로 변경 합니다. 또한 localStorage를 이용하여 페이지 전환 혹은 재 진입 시에도 테마가 적용 될 수 있도록 설정합니다.
const onChange = () => {
if (document.documentElement.getAttribute('data-theme') === 'dark') {
localStorage.setItem('scssTest', 'light');
document.documentElement.setAttribute('data-theme', 'light');
} else {
localStorage.setItem('scssTest', 'dark');
document.documentElement.setAttribute('data-theme', 'dark');
}
};
useEffect(() => {
document.documentElement.setAttribute('data-theme', localStorage.getItem('scssTest'));
}, []);
아래는 onChange 함수를 받을 스위치 HTML 코드입니다.
<div>
<input type="checkbox" id="switch" name="mode" onChange={onChange} />
<label htmlFor="switch">Toggle</label>
</div>
Light Dark CSS Switch
CSS에서 data-* 속성을 선택자[data-*=’속성값’] 과 같이 접근합니다.
html[data-theme='light'] {
div:has(.ag-cell) {
background-color: #fff;
color: #acacac;
}
}
html[data-theme='dark'] {
div:has(.ag-cell) {
background-color: cornflowerblue;
color: #e91e63;
}
}
728x90
반응형
'CSS' 카테고리의 다른 글
Module CSS Use Mixin Include SCSS (0) | 2024.05.30 |
---|---|
Input Radio Custom Css React Component (0) | 2024.03.06 |