简体   繁体   中英

Toggle Class when click on element itself and remove when click outside

I have a list of dom element:

  • 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");

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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