从<li>点击切换div jQuery

时间:2016-03-08 22:31:06

标签: jquery menu toggle addclass

我试图添加课程&#34; open-height&#34;当我在列表项之间单击时,到div并保持类。然后在单击相同的列表项时删除该类。

Fiddle

$('#navlist a').click(function(e) {
    e.preventDefault(); //prevent the link from being followed
    $('#navlist a').removeClass('selected');
    $(this).addClass('selected');

    if($(this).hasClass('selected')) {
      $('.single-course-wrapp').toggleClass('open-height');
    } else {
      $('.single-course-wrapp').addClass('open-height');
    }
});

1 个答案:

答案 0 :(得分:1)

<强> Working fiddle

你可以使用data-*属性来实现这一点,通过将div的id存储在div中的data-opened-by属性上,然后在被点击的项目存储相同的id时使条件从中移除类在数据属性:

&#13;
&#13;
$('#navlist a').click(function(e) {
    e.preventDefault(); //prevent the link from being followed
    
    $('#navlist a').removeClass('selected');
    $(this).addClass('selected');
    
    if($('.single-course-wrapp').hasClass('open-height')){
    		var opener_id = $('.single-course-wrapp').data('opened-by');
       
        if($(this).parent().attr('id')==opener_id){
        		$('.single-course-wrapp').removeClass('open-height');
        }
    }else{
        $('.single-course-wrapp').addClass('open-height');
        $('.single-course-wrapp').data('opened-by', $(this).parent().attr('id'));
    }
});
                                  
&#13;
.nav { color: green; }
.selected { color: red; }
.open-height{
  height:200px;
  width:200px;
  background:#000;
  transition: all 0.6s ease 0.3s;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="navlist">
    <li id="home"><a class="nav" href="home">Home</a></li>
    <li id="about"><a class="nav" href="about-us">About Us</a></li>
    <li id="service"><a class="nav" href="about-us">Service</a></li>
    <li id="contact"><a class="nav" href="about-us">Contact</a></li>
</ul>
<div class="single-course-wrapp">
</div>
&#13;
&#13;
&#13;