提问者:小点点

加载时自动切换展开/折叠箭头


我创建了一个由某些菜单项组成的垂直列表菜单。单击任何菜单项时,列表将展开以显示其内部子菜单项。

还有,当页面加载时,其中一个菜单会根据页面自动展开。我使用了jquery toggle来实现这个功能,它工作得很好。

现在,我用这个菜单放置了折叠/展开箭头,类似于jquery accordian中的菜单,它们在click事件时切换。

我的问题是,当页面加载时,其中一个菜单项折叠,但箭头没有随之折叠,当我再次单击该菜单以折叠/切换回时,箭头开始切换。

情况可以看作,在加载窗口-

菜单1

子菜单

子菜单

子菜单

菜单2

菜单3

菜单4

如您所见,menu1的箭头未关闭。

我的密码到现在为止-

<ul>
<div class="option-heading">
  <li onclick="menu()"> //menu is the vertical menu which shows up.
      <a href="#" >
        <div class="arrow-up">&#9658;</div>
        <div style="display: none;" class="arrow-down">&#9660;</div>
      </a>
  </li>
  </div> 
</ul>    

<script>
$(document).ready(function() {
     $(".option-heading").click(function(){
     $(this).find(".arrow-up, .arrow-down").toggle();
});
});

我用了。加载,但它一次就把所有的箭都展开了。

我想知道的是在加载窗口时切换特定元素的方法。这样其他元素就不会受到影响。就像现在的情况是用箭一样。每当load事件被触发时,它就会切换所有箭头。


共2个答案

匿名用户

$(this).option-heading;任何选项-标题(这就是为什么所有箭头都被切换的原因)。您应该将一个类添加到活动选项标题中,使其唯一。

下面这样的方法可以起到作用:

$(document).ready(function() {
   $(".option-heading").click(function(){
     $(".option-heading").removeClass("active");
     $(this).addClass("active");
     $(".option-heading.active").find(".arrow-up, .arrow-down").toggle();
   });
});

匿名用户

我觉得最好用一个div来显示箭头,看看这个:

<div class="arrow expanded"></div>
or
<div class="arrow"></div>

在CSS样式中:

div.arrow {       /* default/collapsed style */
    width: 20px;
    height: 20px;
    backgound: url('address of collapse image'); /* if use image for arrow */
    /* content: &#9658;  */ /* if use special character */
}

div.arrow.expanded { /* expanded style */
    backgound: url('address of expand image'); /* if use image for arrow */
    /* content: &#9660;  */ /* if use special character */
}

使用此方法,您可以通过以下方式轻松切换箭头图标:

$('div.arrow').toggleClass('expanded');

也可以通过以下方式选中“展开/折叠”:

var isExpanded = $('div.arrow').is('.expanded');