在包含div和图片上切换开/关状态

3
我正在尝试使用CSS和JavaScript添加/删除活动类以突出显示当前图像。我将我的解决方案上传到jsfiddle,请查看它。真的很想了解其中的问题。以下是需要翻译的HTML代码:

我正在尝试使用CSS和JavaScript添加/删除活动类以突出显示当前图像。

我将我的解决方案上传到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;
}​
3个回答

5

siblings不能使用,因为你的锚点被包含在

中。尝试使用:

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

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

演示。(这是一个新的示例,因为你没有发布你的)


4

尝试以下代码:

点击时,它会从所有图像中删除活动类,然后将其应用于当前图像。此外,我认为您根本不需要make_button_active函数。

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

DEMO


1

如果你把代码改成这样,至少它能工作:

 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
哦,我没有收到有关新答案的更新通知,其他解决方案似乎更好。 - Daniel Figueroa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接