HTML
<head>
<style type="text/css>
@import url("style.css") //my main css file
</style>
// css file which contains only color properties.
<link href="theme_blue.css" rel="stylesheet">
</head>
<body>
<a href="#" id="theme-blue">Click Here to switch color</a>
</body>
CSS (theme_blue.css)
body
{
background-color:#66ccff;
}
JS
$(document).ready(function() {
$("#theme-blue").click(function() {
$("link").attr("href", "theme_blue.css");
return false;
});
});
我的问题是,当我点击链接时,网页的整个结构都丢失了,颜色也没有发生变化。我对这项技术很陌生,需要专家的帮助。请建议我解决这个问题的解决方案。
最佳答案
您的问题出在您的 jQuery 选择器上。您正在将属性 href 应用于所有链接元素,包括您的主 css 链接。我建议您提供您的链接和 ID,然后更新您的选择器:
html
<head>
<style type="text/css>
@import url("style.css") //my main css file
</style>
// css file which contains only color properties.
<link id="css_theme_blue" href="theme_blue.css" rel="stylesheet">
</head>
<body>
<a href="#" id="theme-blue">Click Here to switch color</a>
</body>
jQuery
$(document).ready(function() {
$("#theme-blue").click(function() {
$("#css_theme_blue").attr("href", "theme_blue.css");
return false;
});
});
我可以提供另一种我实践过的解决方案吗。
我有自己的样式表,但我更改了 body 类以反射(reflect)我希望特定元素的外观。
body.blue_theme #element_1 {
background:blue;
}
body.green_theme #element_2 {
background: green;
}
然后当我想改变主题时我换掉 body 类:
$('#blue-theme-button').on('click', function() {
$(body).removeClass('green_theme').addClass('blue_theme');
}
这种方法对我来说更可取,因为所有样式都在开始时加载,并且加载新样式表时不会在较慢的机器上暂停。
关于javascript - 我需要在单击页面中的链接时切换样式表,以便页面以不同的颜色主题显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25992074/