【问题标题】:Change the name of CSS import dynamically using jquery使用 jquery 动态更改 CSS 导入的名称
【发布时间】:2020-04-15 07:56:57
【问题描述】:

我想使用 jquery 动态更改 CSS 导入的名称。 来自

HTML

<div class="theme-pallete">
   <button class="blue active" data-theme="Theme">Blue</button>
   <button class="golden" data-theme="goldenTheme">Golden</button>
   <button class="purple" data-theme="purpleTheme">Purple</button>
   <button class="pink" data-theme="pinkTheme">Pink</button>
   <button class="red" data-theme="redTheme">Theme</button>
</div>

jQuery

$('.theme-pallete button').on('click', function () {
    var sheetName = $(this).attr('data-theme');
    $('link[href$="Theme.css"]').attr('href', '/css/' + sheetName + '.css');
});

它在本地系统上运行良好,但是当 Base Url 出现时出现问题

请注意,我不想硬编码基本 URL,因为它会根据托管环境而变化,例如

app.project.com/baseurl/css/Theme.css
app.project.com/UAT/css/Theme.css
app.project.com/design/css/Theme.css

【问题讨论】:

    标签: jquery html css


    【解决方案1】:

    您可以使用function(其中第二个参数是旧值)并替换该方法。

    $('.theme-pallete button').on('click', function () {
        var sheetName = 'blueTheme';
        $('link[href$="Theme.css"]').attr('href', (i, value) => value.replace(/Theme\.css$/, sheetName + '.css');
    });
    

    【讨论】:

    • 我喜欢这种方法。第一次工作得很好,但是变量 sheetName 的值在单击按钮时会不断动态变化。我已经更新了代码。请相应地修改您的答案。
    【解决方案2】:

    只需将主题名称替换为新名称即可

    function changeCssURL(themename){
     $("button").click(function(){
       $('link[href$="Theme.css"]').attr("href", "app.project.com/UAT/css/"+themename+".css");
      });
    }
    

    【讨论】:

    • 任何不需要硬编码 baseurl app.project.com/UAT/ 的解决方案,因为它不适用于 app.project.com/design/css/Theme.css
    • 你可以使用会话变量吗?如果是,那么你做一些像这样的事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多