-5

由于选择列表中的用户选择,我想更改 CSS 文件:

<select>
<option>light</option>
<option>dark</option>
</select>

so when chosen light the css file will be light.css and when Dark so dark.css And save this coice in the cookies or whatever . 谢谢 !

4

2 回答 2

1

您可以在样式表上设置禁用属性,这将禁用该样式表

假设您有两个样式表

<link rel="stylesheet" type="text/css" href="light-theme.css" id="light-theme"/>
<link rel="stylesheet" type="text/css" href="dark-theme.css" id="dark-theme"/>

您可以轻松地启用其中一个

function setTheme(theme) {
    var themes = ["light-theme", "dark-theme"];
    for (var i=0; i < themes.length; i++) {

      var styleSheet = document.getElementById(themes[i]);
      if (themes[i] == theme) {
        styleSheet.removeAttribute("disabled");
      } else {
        styleSheet.setAttribute("disabled", "disabled");
      }      
    }
}

请参阅如何在运行时使用 css 更改和维护多个颜色主题?

您仍然需要将其保存到 cookie 中,您可以为此提出另一个问题。

于 2013-05-29T16:19:21.973 回答
0

实现这一点的最简单方法是挂钩元素的onchange事件select,并使用它在元素上设置特定于主题的类<body>,从而从样式表中应用其他样式。或者,您可以销毁样式表并动态重新加载样式表,但这是一个更高级的主题。

由于您将此问题标记为,因此还值得一提的是,通常您只需为此回发到服务器,在那里更改一些会话/cookie 数据,并基于此在您的模板中生成另一个<link>标签。<head>

提到的两个选项都是解决该问题的有效方法。

于 2013-05-29T16:17:12.357 回答