2012-11-30 19 views
3

我想突出顯示通過使用css,javascript添加/刪除活動類來突出顯示的當前圖像。在包含div和圖像時打開/關閉

我上傳了我的解決方案到jsfiddle,請看看它。真的想明白這是什麼問題。 http://jsfiddle.net/BEmXZ/39/

HTML

<div class="container-thumbs"> 
    <div><a><img src=".jpg" /></a></div> 
    <div><a class="active"><img src=".jpg" /></a></div> 
    <div><a><img src=".jpg" /></a></div> 
</div> 

的Javascript

var make_button_active = function() { 
    //Get item siblings 
    var siblings =($(this).siblings()); 
    //Remove active class on all buttons 
    siblings.each(function (index) { 
      $(this).removeClass('active'); 
     } 
    ); 

    //Add the clicked button class 
    $(this).addClass('active'); 
} 

$(document).ready(function() { 
    $(".container-thumbs a").click(make_button_active); 
}); 

CSS

.container-thumbs{ 
    width: 300px; height: 25; font-size: 18px; 
} 
.container-thumbs a{ 
    list-style: none; float: left; margin-right: 4px; padding: 5px; 
} 
.container-thumbs div a:hover, .container-thumbs div a.active { 
    background-color: #f90; 
}​ 
+1

有沒有小提琴的網址 –

+1

我剛剛更新了! sry –

回答

5

siblings將無法​​正常工作,因爲您的錨是用div包裹的。嘗試:

var make_button_active = function() { 
    $(".container-thumbs a").removeClass("active"); 
    $(this).addClass("active"); 
} 

$(document).ready(function() { 
    $(".container-thumbs a").click(make_button_active); 
});​ 

Demo.(新小提琴,因爲你還沒有發佈你的)

4

試試這個代碼:

點擊之後,它從所有圖像刪除活動類則適用於當前圖像。另外我覺得你根本不需要make_button_active函數。

$(document).ready(function() { 
    $(".container-thumbs a").click(function(){ 
     $(".container-thumbs a").removeClass("active"); 
     $(this).addClass("active"); 
    }); 
});​ 

DEMO

1

,如果你的代碼更改爲這它的工作原理ATLEAST:

var make_button_active = function() 
{ 
    //Get item siblings 

    var siblings = $(".container-thumbs a");  
    siblings.each(function (index) 
{ 
    $(this).removeClass('active'); 
} 
); 
    $(this).addClass('active'); 
} 

$(document).ready(function() { 
$(".container-thumbs a").click(make_button_active); 

});

+1

哦,沒有得到有關新答案的更新通知,其他解決方案看起來好多了。 –