如何使用JQuery使一个类一次处于活动状态?

时间:2013-05-23 21:52:37

标签: javascript jquery addclass removeclass toggleclass

代码:

var $anchors = $(".box_one, .box_two");

$(document).on('click', function (e) {
    var $elem = $(e.target);
    if ($elem.hasClass('box_one') || $elem.hasClass('box_one_active')) {
        $elem.toggleClass('box_one box_one_active');
        $anchors.not($elem).addClass('box_two').removeClass('box_two_active');
    }
    else if($elem.hasClass('box_two') || $elem.hasClass('box_two_active')) {
        $elem.toggleClass('box_two box_two_active');
        $anchors.not($elem).addClass('box_one').removeClass('box_one_active');
    }
    else {
        $('.box_one_active').addClass('box_one').removeClass('box_one_active');
        $('.box_two_active').addClass('box_two').removeClass('box_two_active');
    }
});

在上面的代码中,当box_one被点击时,box_one_active会占用box_one的位置,当box_two被点击时,box_two_active会选择box_two的位置。

如何更改代码,以便在box_one_active 有效box_two_active 同时 。这意味着,用户必须单击一个以禁用另一个并启用另一个。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

我建议不要这样做。相反,只需切换活动类,然后编写CSS以代替类的组合。

以下是一个例子:Live Copy | Live Source

CSS:

.box_one {
  /* Styles for `box_one` when not active */
  background: blue;
  color: white;
  font-weight: bold;
}
.box_one.active {
  /* Adds/overrides further classes for when `box_one` is also `active` */
  border: 2px solid red;
}
.box_two {
  /* Styles for `box_two` when not active */
  background: green;
  color: white;
  font-weight: bold;
}
.box_two.active {
  /* Adds/overrides further classes for when `box_two` is also `active` */
  border: 2px solid yellow;
}

HTML:

<div class="box_one">This is box_one</div>
<div class="box_two">This is box_two</div>

JavaScript的:

$("div").click(function() {
    $(".active").removeClass("active");
    $(this).addClass("active");
});

请注意添加和删除“活动”类是如何改变的。

在上面我不是覆盖样式,但你可以:Live Copy | Live Source

.box_one {
  /* Styles for `box_one` when not active */
  background: blue;
  color: white;
  font-weight: bold;
}
.box_one.active {
  /* Adds/overrides further classes for when `box_one` is also `active` */
  background: red;
}
.box_two {
  /* Styles for `box_two` when not active */
  background: green;
  color: white;
  font-weight: bold;
}
.box_two.active {
  /* Adds/overrides further classes for when `box_two` is also `active` */
  background: yellow;
}

答案 1 :(得分:0)

您可以使用活动选择器删除活动类的所有痕迹。

在您的情况下,您的活动类正在发生变化,这会使事情变得复杂。

你可以制作活跃的课程.box_active,这会大大简化事情。

然后将其删除,请执行

$('.box_active').removeClass('box_active');