![](/img/trans.png)
[英]Show/hide div's with javascript on a button press (and switch between the buttons)
[英]switch between 2 div's
我想在2個div之間切換,這樣當我點擊其中一個時,它的邊框和標題變成紅色,我希望另一個div消失。 所以它就像是他們之間的選擇我不知道我做錯了我添加(IF)所以我可以讓它發生但它不起作用請幫助我。
$(".container").on("click" , function(){ $(this).toggleClass("active"); $(".header", this).toggleClass("active2"); if ($(".box1").hasClass("active")) { $(".box2").removeClass("active"); $("h2", ".box2").removeClass("active2"); }if ($(".box2").hasClass("active")) { $(".box1").removeClass("active"); $("h2", ".box1").removeClass("active2"); } });
body{ padding: 3em; } .box1, .box2{ padding: 2em; border: 1px solid silver; margin-top: 2em; } .active{ border-color: red; } .active2{ color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container box1"> <h2 class="header">Boys</h2> <hr> <p>Benjamin</p> <p>David</p> </div> <div class="container box2"> <h2 class="header">Girls</h2> <hr> <p>Sara</p> <p>Tania</p> </div>
您不需要很多代碼就可以完成這項工作。 將.active
添加到單擊元素並從兄弟中移除類。
$(".container").on("click", function() { $(this).toggleClass("active").siblings().removeClass("active"); });
body{padding: 3em} .box1, .box2{ padding: 2em; border: 1px solid silver; margin-top: 2em; } .active {border-color: red} .active .header{color: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container box1"> <h2 class="header">Boys</h2> <hr> <p>Benjamin</p> <p>David</p> </div> <div class="container box2"> <h2 class="header">Girls</h2> <hr> <p>Sara</p> <p>Tania</p> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.