2013-06-25 32 views
0

點擊一個按鈕(除了被點擊的按鈕除外)後,我需要更改所有按鈕的不透明度。使用jQuery更改元素不透明度

下面是HTML代碼:

<button data-target="Section1" class="metro-button">Button1</button> 
<button data-target="Section2" class="metro-button">Button2</button> 
<button data-target="Section3" class="metro-button">Button3</button> 

和jQuery代碼:

$(".metro-button").click(function(){ 
    var buttons = document.getElementsByClassName("metro-button"); 
    for(i = 0 ; i < buttons.length ; i++) { 
     if ($(this).attr('data-target') != buttons[i].attr('data-target')) { 
      buttons[i].animate({"opacity" : 0.3}); 
     } 
    } 
}); 

Demo in JsFiddle.

問題是什麼?

任何想法,將不勝感激。使用jQuery

+2

你爲什麼要通過每一個按鈕時,搜索你點擊一個?只需使用您點擊的那個'this'。 –

+3

[瞭解如何**調試** JavaScript](http://www.netmagazine.com/tutorials/javascript-debugging-beginners)。 –

回答

5

$(".metro-button").click(function(){ 
    $(".metro-button").not(this).animate({"opacity" : 0.3}); 
    $(this).animate({"opacity" : 1}); 
}); 

FIDDLE

1

可能是一個解決方案也是如此,這取決於你的HTML結構:

DEMO

$(".metro-button").click(function() { 
    $(this).animate({ 
     "opacity": 1 
    }).siblings('.metro-button').animate({ 
     "opacity": .3 
    }) 
});