2014-07-09 151 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