如果已经激活JS,请停止切换

时间:2018-08-07 20:52:48

标签: javascript jquery html css

我想在同级兄弟之间切换课程,但是如果其中一个已经添加了calss,我希望它不能更改。

示例:(如果您单击一个已经打开的div,它会关闭。我需要,如果一个div打开,您将无法关闭它,只能单击另一个div关闭第一个div并打开新的div)帮助?

$(document).ready(function() {
	$('.sfb2').click(function() {
		$(this).toggleClass('sfb-active');
		$(this).siblings().removeClass('sfb-active');
	});
});
.flex {
  display: flex;
}
.center {
  margin: auto;
}
.sfb1 {
	width: 99.8%;
	height: 400px;
}
.sfb2 {
	flex: 1;
	margin: 0px 6px;
	transition: flex .4s cubic-bezier(0.61,-0.19,0.7,-0.11);
	background-size: 1200px;
	background-position: center;
	background-repeat: no-repeat;
	border-radius: 2px;
	border: 1px solid rgba(0,0,0,0.1);
	background: rgba(0,0,0,0.1);
}
.sfb-active {
	flex: 5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="sfb1 flex center">
  <div class="sfb2 sfb-i1 sfb-active">

  </div>
  <div class="sfb2 sfb-i2">

  </div>
  <div class="sfb2 sfb-i3">

  </div>
  <div class="sfb2 sfb-i4">

  </div>
  <div class="sfb2 sfb-i5">

  </div>
</div>

2 个答案:

答案 0 :(得分:1)

只需检查元素是否具有类,否则请执行代码。
!$(this).hasClass('sfb-active'){...}

在这里,this上下文指向被单击元素本身

$(document).ready(function() {
	$('.sfb2').click(function() {
    if (!$(this).hasClass("sfb-active")){
      $(this).toggleClass('sfb-active');
      $(this).siblings().removeClass('sfb-active');
    }
	});
});
.flex {
  display: flex;
}
.center {
  margin: auto;
}
.sfb1 {
	width: 99.8%;
	height: 400px;
}
.sfb2 {
	flex: 1;
	margin: 0px 6px;
	transition: flex .4s cubic-bezier(0.61,-0.19,0.7,-0.11);
	background-size: 1200px;
	background-position: center;
	background-repeat: no-repeat;
	border-radius: 2px;
	border: 1px solid rgba(0,0,0,0.1);
	background: rgba(0,0,0,0.1);
}
.sfb-active {
	flex: 5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="sfb1 flex center">
  <div class="sfb2 sfb-i1 sfb-active">

  </div>
  <div class="sfb2 sfb-i2">

  </div>
  <div class="sfb2 sfb-i3">

  </div>
  <div class="sfb2 sfb-i4">

  </div>
  <div class="sfb2 sfb-i5">

  </div>
</div>

答案 1 :(得分:0)

在添加元素之前检查该元素是否具有类sfb-active

$('.sfb2').click(function(e) {
    if (!$(e.target).hasClass('sfb-active')) {
        $(this).toggleClass('sfb-active');
        $(this).siblings().removeClass('sfb-active');
    }
});