Jquery和CSS切换 - 这可能吗?

I build a css file using PHP which allows me to easily customize the color of many elements. Is it possible for me to "rebuild" the stylesheet and apply it to the page in the DOM using Jquery?

eg.

<?php
if (isset($_POST['mycolor'])){
$myColor = $_POST['mycolor'];
} else {
$myColor = "blue";
}
?>

<style type='text/css'>
    .style1{
    color:<?php $myColor;?>;
    }
</style>

Now on my page I have a link you can click called "change color to red" and when you click "red" it does a $.post to my php script, which rebuilds the css including .style1 - and allows the page to change the stylesheet.

I haven't tested this but would it even work? If I echo'ed out the new stylesheet after the post into the dom... would it even apply to the page?

You can do something like this if your whole stylesheet is php generated:

function newCSS(params){
  $("link[href*=myStyles.php]:last").after('<link href="myStyles.php?'+ params +'" type="text/css" rel="Stylesheet" />');
  $("link[href*=myStyles.php]:first").remove();
}

This replaces the link in the head with the new one...the new styles will take effect once it's loaded.

You could use the css function to set different css properties on elements:

$('.style1').css('color', 'red');

I recommend you to create your dynamic css as a php-file. More info here: http://www.barelyfitz.com/projects/csscolor/

EDIT: Here's an improved solution using selector provided by Nick:

$("link[href*=myStyles.php]").attr('href','myStyles.php');

I don't know if you've ever heard about LESS. It's a nice little tool that makes it possible for you to have "variables" in your CSS. Which seems to be what you are really wanting.

Have a look at This blog post which should help you.