我目前能够直接通过JS动态更改样式规则,但我发现这进一步限制,我宁愿能够热插拔整个CSS样式表文件。有什么建议吗?
我的代码:
<label>Themes :</label>
<select name="background" id="bg" onchange="changeBg(this)">
<option value="white">Default</option>
<option value="#444">Dark</option>
<option value="teal">Teal</option>
</select>
// Changing Themes
function changeBg(x){
var body = document.getElementById('body');
body.style.backgroundColor = x.value;
}
也许我有多个样式表定义,如下所示:
<!-- Themes -->
<link type="text/css" rel="stylesheet" media="all" href="style.css" id="theme1_css">
<link type="text/css" rel="stylesheet" media="all" href="themes/dark.css" id="theme2_css">
<link type="text/css" rel="stylesheet" media="all" href="themes/teal.css" id="theme3_css">
答案 0 :(得分:0)
所以我将js脚本编辑成:
// Changing Themes
function changeBg(x){
var link = document.getElementById('theme1_css');
link.href = 'themes/' + x.value + '.css';
}
信用:感谢@Pete
答案 1 :(得分:0)
基本思想是您可以使用disabled
属性设置/取消设置主题:
<link rel="stylesheet" type="text/css" href="dark.css" data-theme="dark">
<link rel="stylesheet" type="text/css" href="light.css" data-theme="light">
和
function setTheme(theme) {
var styles = document.querySelectorAll('link[rel="stylesheet"]');
styles.forEach(function(style) {
var styleTheme = style.getAttribute('data-theme');
style.disabled = styleTheme && styleTheme !== theme;
});
}
现在用以下内容设置主题:
setTheme('light');