How to dynamically change themes after clicking a drop down menu of themes

前端 未结 6 1172
甜味超标
甜味超标 2020-12-12 18:01

I\'m using bootstrap for the interface of the website I\'m developing. I am also planning to integrate the bootswatch themes to my site. I have created a dropdown menu conta

6条回答
  •  情书的邮戳
    2020-12-12 19:03

    Fiddle:http://jsfiddle.net/82AsF/ (click the themes dropdown in the navbar)
    Give your links a class theme-link and a data-theme value of the theme name like so:

    Amelia
    

    Then, define your themes in a global variable like so:

    var themes = {
        "default": "//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css",
        "amelia" : "//bootswatch.com/amelia/bootstrap.min.css",
        "cerulean" : "//bootswatch.com/cerulean/bootstrap.min.css",
        "cosmo" : "//bootswatch.com/cosmo/bootstrap.min.css",
        "cyborg" : "//bootswatch.com/cyborg/bootstrap.min.css",
        "flatly" : "//bootswatch.com/flatly/bootstrap.min.css",
        "journal" : "//bootswatch.com/journal/bootstrap.min.css",
        "readable" : "//bootswatch.com/readable/bootstrap.min.css",
        "simplex" : "//bootswatch.com/simplex/bootstrap.min.css",
        "slate" : "//bootswatch.com/slate/bootstrap.min.css",
        "spacelab" : "//bootswatch.com/spacelab/bootstrap.min.css",
        "united" : "//bootswatch.com/united/bootstrap.min.css"
    }
    

    (please host these bootswatch css files on your own server when you do this - I'm only hotlinking because I don't have a server on hand)
    Then, use the following jQuery code:

    $(function(){
       var themesheet = $('');
        themesheet.appendTo('head');
        $('.theme-link').click(function(){
           var themeurl = themes[$(this).attr('data-theme')]; 
            themesheet.attr('href',themeurl);
        });
    });
    

提交回复
热议问题