简体   繁体   English

单击元素本身时切换类,单击外部时删除

[英]Toggle Class when click on element itself and remove when click outside

I have a list of dom element:我有一个 dom 元素列表:

  • When I click on the element, it will toggle open and close.当我单击该元素时,它将切换打开和关闭。
  • When I click on the child of the open one, it will not close the parent.当我单击打开的子项时,它不会关闭父项。
  • When I click on another one, it will open the one which is clicked and close the others.当我点击另一个时,它会打开被点击的那个并关闭其他的。
  • When I click outside the element that has been opened, it will close then open.当我在已打开的元素外部单击时,它将关闭然后打开。

-> The problem is I can't archive the first one. -> 问题是我无法存档第一个。 Does somebody know what I'm doing wrong here?有人知道我在这里做错了什么吗?

 $(".front").click(function() { $(".front").not(this).removeClass("active"); $(this).addClass("active"); }); $(document).mouseup(function(n) { var t = []; t.push($(".front")); $.each(t, function(t, i) { $(i).is(n.target) || $(i).has(n.target).length !== 0 || $(i).removeClass("active") }) });
 .front { position: relative; background-color: red; width: 100px; height: 100px; margin: 20px; } .front .back { position: absolute; top: 50%; left: 150px; display: none; background-color: green; width: 50px; height: 50px; } .front.active .back { display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="front"> <div class="back"></div> </div> <div class="front"> <div class="back"></div> </div> <div class="front"> <div class="back"></div> </div>

just add toggle class after your first line:只需在第一行后添加切换类:

$(".front").click(function() {
$(".front").not(this).removeClass("active");
$(this).toggleClass("active");

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM