2014-07-09 152 views
3

使用removeClass和addClass我想,一旦它被点击,突出一个按钮和一个特定的类添加到<div>classitem为好。如何通过点击按钮

HTML

<button type="button" class="btn gridLarge">largegrid</button> 
<button type="button" class="btn grid active">smallgrid</button> 
<button type="button" class="btn list">list</button> 
<div class="item">text</div> 

CSS

.item{ 
    height:240px; 
    border:1px solid orange; 
} 
.item.list{ 
    width:600px; 
    height:500px; 
    border:1px solid red; 
} 
.item.gird{ 
    width:400px; 
    height:500px; 
    border:1px solid red; 
} 
.item.gridlarge{ 
    width:500px; 
    height:500px; 
    border:1px solid red; 
} 

button{ 
    cursor:pointer; 
    border:1px solid green; 
    padding:20px; 
    color:red; 
    margin-bottom:20px; 
} 

.btn.active{ 
    color:green; 
    background-color:red; 
} 

例如

  1. 当点击button.gridLarge,我想highlig HT它(通过添加类active)和类.gridLarge添加到div.item
  2. 当点击button.grid,我想强调它和类.grid添加到div.item
  3. 当点击button.list,我想强调它和类.list添加到div.item

下面的代码我到目前为止:JSFiddle

+2

__I不应该回答了.__但这里的东西给你与http://jsfiddle.net/satpalsingh/XG6Jn/ – Satpal

+0

是的,先生玩..但我也(.item)是addClass格,列表,大网格.. – JavaEagle

+0

你明白。我的意思是(.item)是Css类。 – JavaEagle

回答

2

如果应用类添加为id的按钮,你可以做到以下几点:

$('.btn').click(function(){ 
    $('.active').removeClass('active'); 
    $(this).addClass('active'); 
    $('.item').removeClass().addClass('item').addClass(this.id); 
}); 

Demo

侧面说明:你有在你的CSS一个错字,类在第二个按钮是grid,在CSS其gird

+0

这让我想起了关于在点击按钮上设置'.active'类并从之前点击删除的提示。 – Silveraven

+0

谢谢先生。这是我想要的..非常感谢你。 – JavaEagle

+0

为什么不简单'removeClass()'而不是'attr('class',“”)'? – Satpal

1

DEMO

最佳做法是使用data-yourVariableName(我的DEMO中为data-class)属性来查看代码将使用的数据。然后你只是写这样的事情:

$("button").click(function(){ 
    $(".item").toggleClass($(this).attr('data-class')); 
}); 

这是jQuery代码。如果你不熟悉,这是他们的API

2

您可以通过attr一个得到class然后删除btn类以获得其他class名称。但是,我更喜欢在data属性中保存类名。

Demo

HTML:

<button type="button" data-class="gridLarge" class="btn gridLarge active">largegrid</button> 
<button type="button" data-class="grid" class="btn grid">smallgrid</button> 
<button type="button" data-class="list" class="btn list">list</button> 
<div class="item"></div> 

的Javascript:

$('.btn').click(function() { 
    var $this = $(this); 

    $('.btn').removeClass('active'); 
    $this.addClass('active'); 

    $('.item').removeClass('gridLarge grid list').addClass($this.data('class')); 
}); 

CSS:

.item { 
    height:240px; 
    border:1px solid orange; 
} 
.item.list { 
    width:600px; 
    height:500px; 
    border:1px solid red; 
} 
.item.grid { 
    width:400px; 
    height:500px; 
    border:1px solid red; 
} 
.item.gridlarge { 
    width:500px; 
    height:500px; 
    border:1px solid red; 
} 
button { 
    cursor:pointer; 
    border:1px solid green; 
    padding:20px; 
    color:red; 
    margin-bottom:20px; 
} 
.btn.active { 
    color:green; 
    background-color:red; 
} 
+0

谢谢先生..这是我想要的.. – JavaEagle