jQuery 将外部 css 文件附加到所有 HTML 页面

jQuery append external css file to all HTML pages

我有 2 个不同的 CSS 文件给 2 个客户

如果我 select 选项 1 来自 索引器页面 ,html 页面内的所有内容应附加在 css 文件:

<link rel="stylesheet" type="text/css" href="css/client1.css">

或者如果我 select 选项 2,那么它应该在 css 文件下面加载:

<link rel="stylesheet" type="text/css" href="css/client2.css">

但是,必须对 pages/

下的所有 html 文件进行此更改

Indexer.html

<select class="selInput" id="selectClient">
    <option>-- Select Client --</option>
    <option value="client1">Client 1</option>
    <option value="client2">Client 2</option>
</select>

<script>
$(document).ready(function(){

    $( document ).on( "change", "#selectClient", function(){
        jQuery(this).find("option:selected").each(function(){
            if($(this).attr("value")=="client1-script"){
                $("body").load("css/client1.css");
            }
            else if($(this).attr("value")=="client2-script"){
                $("body").load("css/client2.css");
            }
        });
    });

});

</script>

您有两个选择:

  1. 加载两者 CSS 并使用 类 来区分它们。

    考虑 client1.css:

    body.client1 { /* rules */ }
    body.client1 h1 { /* rules */ }
    body.client1 p { /* rules */ }
    body.client1 ul,
    body.client1 ol { /* rules */ }
    

    考虑 client2.css:

    body.client2 { /* rules */ }
    body.client2 h1 { /* rules */ }
    body.client2 p { /* rules */ }
    body.client2 ul,
    body.client2 ol { /* rules */ }
    

    在你的 HTML 中:

    <body class="client1"> <!-- if client 1 -->
    <body class="client2"> <!-- if client 2 -->
    

    在你的JavaScript中:

    $(function () {
        $("body").on("change", "#selectClient", function () {
            $("#body").removeClass("client1 client2").addClass("client" + $(this).val());
        });
    });
    
  2. 使用 <link />id 并更改 href.

    在你的<head>中:

    <link rel="stylesheet" type="text/css" href="css/client1.css" id="style" />
    

    在你的JavaScript中:

    $(function () {
        $("body").on("change", "#selectClient", function () {
            $("#style").attr("href", "css/client" + $(this).val() + ".css");
        });
    });