我有这个:
<html lang="en" theme="dark">
和此:
html {
&[theme='light'] {
--bg: #ffffff;
--title: #6822c4;
--sub-title: #000000;
--text: #ffffff;
}
&[theme='dark'] {
--bg: #17171F;
--title: #4578a5;
--sub-title: #acacac;
--text: #ffdddd;
}
}
和此:
$('#myCheckBox').change(function() {
if ($(this).is(':checked')) document.documentElement.setAttribute('theme', 'dark')
else document.documentElement.setAttribute('theme', 'light')
});
并且运行良好,但是没有过渡,所以我想知道我是否可以使用jQuery处理某些东西,例如fadeOut之类的东西?
您必须在CSS中添加转换
$('#myCheckBox').change(function() {
if ($(this).is(':checked')) $('html').attr('theme', 'dark')
else $('html').attr('theme', 'light')
});
html body {
transition-property: background-color;
transition-duration: 1.5s;
}
html[theme='light'] body {
background: #ffffff;
}
html[theme='dark'] body {
background: #17171F;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html lang="en" theme="dark">
<body>
<input type="checkbox" id="myCheckBox" value="1" checked>
</body>
</html>
向要更改的元素添加transitions:
$('#myCheckBox').change(function() {
if ($(this).is(':checked')) document.documentElement.setAttribute('theme', 'dark')
else document.documentElement.setAttribute('theme', 'light')
});
html[theme='light'] {
--bg: #ffffff;
--title: #6822c4;
--sub-title: #000000;
--text: #000000;
}
html[theme='dark'] {
--bg: #17171F;
--title: #4578a5;
--sub-title: #eeeeee;
--text: #ffffff;
}
body {
background-color: var(--bg);
transition: background-color 600ms linear;
}
label {
color: var(--text);
cursor: pointer;
}
h1 {
color: var(--title);
}
h2 {
color: var(--sub-title);
}
<html lang="en" theme="dark">
<head>
<meta charset="utf-8">
<title>Test</title>
<meta name="description" content="Test">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>Dark theme
<input type="checkbox" id="myCheckBox" name="checkbox_theme" checked>
</label>
<h1>Title</h1>
<h2>Sub-Title</h2>
</body>
</html>