我需要在点击页面中的链接时切换我的样式表,以便页面以不同的颜色主题显示

I need to switch my style sheets on clicking a link in page so that the page is displayed in different color themes

本文关键字:显示 样式 颜色 链接 我的      更新时间:2023-09-26

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.blue_theme #element_1 {
background:blue;
}
body.green_theme #element_2 {
background: green;
}

当我想改变主题时,我会换掉身体类:

$('#blue-theme-button').on('click', function() {
$(body).removeClass('green_theme').addClass('blue_theme');
}

这种方法对我来说更可取,因为所有样式都是在一开始加载的,当加载新样式表时,速度较慢的机器上不会有停顿。

假设/Content文件夹中有两个css文件。

main-theme.css:

body {
   background-color:#fff;
}

blue-theme.css:

body {
   background-color: blue;
}

你有一个默认使用main-theme.css的页面,链接元素有id#siteTheme,还有id#blueTheme 的可点击元素

<link id="siteTheme" href="/Content/main-theme.css" rel="stylesheet" type="text/css" />
<a href="#" id="blueTheme">Activate Blue Theme</a>

您所需要的只是为#blueTheme click编写函数,该函数更改id为#siteTheme:的链接元素的href属性值

<script>
            $(document).ready(function () {
                $("#blueTheme").click(function () {
                    $("#siteTheme").attr("href","/Content/blue-theme.css");
                });
            })
</script>

我希望这会有所帮助;)在编写这些脚本之前,不要忘记加载jquery。

<script src="/Scripts/jquery-1.10.2.min.js"></script>