简体   繁体   中英

using jquery load diffent css?

i have two buttons. now i want the vistor to click the button2, the site invoks the style2.css ,when click button1. invoks the style.css . the default shows the style.css is there a ways to use jquery change the the link path of css.

<link rel="stylesheet" href="http://www.example.com/themes/style.css" type="text/css"/>

if click button2, change the line to < link rel="stylesheet" href="http://www.example.com/themes/style2.css" type="text/css"/>

or other ways to get the effect. thank you

In button2's onclick handler, do this:

$('link').attr('href', 'http://www.example.com/themes/style2.css');

EDIT: Apparently I need to point out that this will affect all link tags if you have more than one, so use an id as your selector if you have more than one link, eg:

<link id="myLink".../>

$('#myLink).attr('href',...);

You could let jQuery change/add a class to your <body> element. This does mean you'll have to have all of the styles in one stylesheet.

For example:

CSS:

.some-style        { color: #f00; }
.blue .some-style  { color: #00f; }
.green .some-style { color: #0f0; }

HTML:

<html>
<body>
    <p class="some-style">Some text</p>
    <button id="btn-1">Blue</button>
    <button id="btn-2">Green</button>
</body>
</html>

Javascript(simplified for example purposes):

$('#btn-1').click(function() {
    $('body').addClass('blue');
});

$('#btn-2').click(function() {
    $('body').addClass('green');
});

Try to put a condition with your php code, like this:

<?if(buttonOneClicked()){?>
<link rel="stylesheet" href="http://www.example.com/themes/style.css" type="text/css"/>
<?}else{?>
<link rel="stylesheet" href="http://www.example.com/themes/style2.css" type="text/css"/>
<?}?>

Pretty good write-up on this basic idea here:

http://www.rickardnilsson.net/post/2008/08/02/Applying-stylesheets-dynamically-with-jQuery.aspx

If you find you cannot remove a css file, you may eed to have your buttons redirect with a url variable your jquery can read and attach the appropriate css file.

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