我创建了一个CSS切换器,但我只需要更改class=“”的元素;红色”;身体


I create a CSS switcher, but I need to change only elements with class="red" for body

我创建了一个CSS切换器,但我只需要为body更改带有class="red"的元素。我该怎么做?

<html>
    <head>
        <jdoc:include type="head" />
        <link href="style.css" rel="stylesheet" type="text/css" />
        <script src="/js/modernizr-2.0.6.custom.min.js"></script>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script src="/js/jquery.cookies.2.2.0.min"></script>
    </head>
    <body class="front">
        <select class="style-change">
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="green">Green</option>
        </select>
        <script>
            $(function(){
                $('.style-change').change(function(){
                    $('link[rel="stylesheet"]')
                        .attr("href", $(this).val() + ".css");
                });
            });
        </script>
    </body>
</html>

演示Here

您可以使用它来更改主体的类。

document.body.className="red"

如果您更喜欢直接的javascript,Moazzam的答案应该可以。如果你喜欢使用jQuery,你可以使用这个:

$('body').removeClass().addClass('red');

或者,为了将其概括为与下拉列表一起使用,下面是:

$(function(){
    $('.style-change').change(function(){
        $('body').removeClass().addClass($(this).val());
   });
});

如果您只想更改body标记类,请更新jquery函数:

$('.style-change').change(function(){
    $('body').removeClass();
    $('body').addClass($(this).val());
});

http://jsfiddle.net/mF9qm/