简体   繁体   中英

How to change the css stylesheet dynamically for a website being viewed?

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.

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

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" />

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.

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;
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM