简体   繁体   中英

JQuery CSS Changer Not Functioning

So I posted a question earlier about this and after a helpfull reponse, I've proceeded to attempt to try the code. I've not used JQuery before so this was a step into the beyond for me.

What I'm doing is using the below code to change the CSS of a website, almost like a template, however, when pressing the buttons, there's no change. I've included the JQuery script linked to Google. The code itself is pretty self explanitory, when you press the button, it should load a different stylesheet. I'm not sure if it's a permanant change or not, but just testing a the moment. Any help is appreciated!

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2'></script>

<script type="text/javascript">

$("button#grayscale").click(function() { 
    $("link[rel=stylesheet2]").attr({href : "css2.css"}); });

$("button#original").click(function() { 
    $("link[rel=stylesheet]").attr({href : "css.css"}); });
});

<button id="original">Original</button><br />
                <button id="grayscale">Grayscale</button>

I think you should follow @undefined's suggestion and apply class prefixes to all your rules. You can then apply the class to an element high up, which means if you change the class everything follows suit:

CSS:

body.grayscale div{
    color: gray;
}

body.normal div{
    color: green;
}

JS:

$("button#original").click(function() { 
    $("body").removeClass("grayscale"); 
    $("body").addClass("normal"); 
});

$("button#grayscale").click(function() { 
    $("body").removeClass("normal"); 
    $("body").addClass("grayscale"); 
});

Something like this would switch the stylesheet but it won't be a permanent change:

HTML:

<div id="theme-switcher">
    <button data-theme="css2.css">Greyscale</button>
    <button data-theme="css.css">Original</button>
</div>

jQuery:

$('#theme-switcher').on('click', 'button', function() {
    $('link[rel=stylesheet]').attr('href', $(this).data('theme'));
});

To make it permanent you could send the value via an AJAX request to a server-side scripted page that saves the value in the database. That value can then be pulled from the database server-side and inserted into the HTML when rendering the <link /> tag.

Updated jQuery with example AJAX:

$('#theme-switcher').on('click', 'button', function() {
    var theme = $(this).data('theme');

    // if it was a PHP based project
    $.post('save-theme.php', { theme: theme }).done(function() {
        $('link[rel=stylesheet]').attr('href', theme);
    });
});

What happens in save-theme.php is server-side stuff so not my area of expertise unfortunately, sorry!

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