按下按钮切换div的类

时间:2012-09-07 16:08:27

标签: javascript class html twitter-bootstrap

我正在使用Twitter Bootstrap制作一些基本网站

我有一个div和两个我想要使用的类。 我想实现改变div类的按钮,然后再次点击,然后将其改回。

找到了很多方法,但没有一个方法可以改变课程。 最好的方法是使用Bootstrap JS或Jquery

由于

2 个答案:

答案 0 :(得分:3)

演示1:http://jsfiddle.net/Jsqh4/
演示2(单独按钮):http://jsfiddle.net/Jsqh4/1/

Bootstrap使用jQuery作为其组件,因此jQuery解决方案可能对您来说最简单。

<style>
    .style1{ background-color: yellow; }
    .style2{ background-color: green; }​
</style>

<div id="div1" class="style1">
    Here is a div.
</div>

<input type="button" id="btn1" value="Click Me" />

<script>
    $("#btn1").click(function(){
        $("#div1").toggleClass("style2");
    });
</script>

另请参阅:http://api.jquery.com/toggleClass/

答案 1 :(得分:0)

不幸的是,对于已接受的答案评论不够......

我会切换这两个类,以避免遗漏任何未被覆盖的样式的风险。

<style>
    .style1{ background-color: yellow; }
    .style2{ background-color: green; }​
</style>

<div id="div1" class="style1">
    Here is a div.
</div>

<input type="button" id="btn1" value="Click Me" />

<script>
    $("#btn1").click(function(){
        $("#div1").toggleClass("style1");
        $("#div1").toggleClass("style2");
    });
</script>
相关问题