How to change the css stylesheet dynamically for a

2019-05-14 07:41发布

问题:

I have a website where users can generate their own Codeigniter websites using a wizard in it users will provide module, fields and functions details. Based on the user input a website will be generated and deployed on my website and a demo will be shown to the user before they go with the download. Everything works fine.

Now I am planning to allow users to choose different styles/themes for the generated website when they are previewing it. How can allow users to see their changes immediately without reloading the entire page?

I tried by replacing their style sheet file on the generated website with the selected style and redirected to another page on the generated website. But the same style sheet file is used since it is already cached by browser. So please give me some options. If that can be done without redirecting the user it will be the best option for me.

回答1:

To prevent the caching issue, the stylesheets need to have different names. Here's an example of how you can implement it using jQuery: http://www.cssnewbie.com/simple-jquery-stylesheet-switcher/

Demo



回答2:

pass a variable to the view, the variable holds the value of the filename of the stylesheet? As far as changing the style file when the user is in the same page... see this question: Is there an easy way to reload css without reloading the page?

<?php
$data['stylesheet_name'] = 'user1';

$this->load->view('viewname', $data);

/**
 * View File
 **/

<link rel="stylesheet" type="text/css" href="/css/user/<?= $stylesheet_name; ?>.css" />


回答3:

I have used the below code and it is working without the need of changing the style sheet file name.

function reloadStylesheets() {
    var queryString = '?reload=' + new Date().getTime();
    $('link[rel="stylesheet"]').each(function () {
        this.href = this.href.replace(/\?.*|$/, queryString);
    });
}

This forces browser to reload the file since the parameter changed because of the time change.



回答4:

This worked for me to replace a single stylesheet. The stylesheets are named "themegray", "themeblue", "themegreen", etc. "t" represents the new color, such as "blue".

function flipTheme(t) {
    $('link[rel="stylesheet"]').each(function () {
        if (this.href.indexOf(theme)>=0) {
            this.href = this.href.replace(theme, t);
            theme = t;
        }
    });
}