如何切换下拉箭头

8
这是我正在使用的代码,用于隐藏和显示带有滑动切换效果的div。
jQuery(document).ready(function() {
    jQuery(".option-content").hide();
    jQuery(".option-heading").click(function()
        {
            jQuery(this).next(".option-content").slideToggle(500);
        });
    });

然而,我想添加一些切换箭头来显示切换的div是向上还是向下。

目前为止,这就是我的代码,它只完成了我希望它完成一半的工作:
jQuery(document).ready(function() {
    jQuery(".option-content").hide();
    jQuery("#arrow-up").hide();
    jQuery(".option-heading").click(function()
        {
            jQuery(this).next(".option-content").slideToggle(500);
            jQuery("#arrow-up").toggle();
            jQuery("#arrow-down").toggle();
        });
});

这将切换箭头,但存在两个问题:

  1. 向下的箭头保持显示
  2. 每个div都切换每个箭头,因此当一些div向上而另一个向下时,它们都显示为向下。

欢迎提出任何想法。

3个回答

20
  • 使用:before伪元素制作装饰性箭头图标
  • 使用jQuery的.toggleClass()

jQuery(function($) { // DOM ready and $ alias in scope

  /**
   * Option dropdowns. Slide toggle
   */
  $(".option-heading").on('click', function() {
    $(this).toggleClass('is-active').next(".option-content").stop().slideToggle(500);
  });

});
.option-heading:before           { content: "\25bc"; }
.option-heading.is-active:before { content: "\25b2"; }

/* Helpers */
.is-hidden { display: none; }
<div class="option-heading">HEADING</div>
<div class="option-content is-hidden">
  content<br>content<br>content<br>content<br>content<br>content<br>content
</div>

<script src="//code.jquery.com/jquery-3.3.1.js"></script>

附言:如果你使用的是一些不同的字体图标(例如icomoon),则需要添加相应的十六进制码,并在:before伪元素中添加font-family: 'icomoon';


2

使用类!

jQuery(document).ready(function() {
    jQuery(".option-content").hide().removeClass("shown").addClass("hidden");
    jQuery(".option-heading").click(function()
        {
            jQuery(this).next(".option-content").slideToggle(500)
                  .removeClass("hidden").addClass("shown");
        });
});

然后使用CSS:

.option-content.hidden{ background-image:url(hidden.png); } 
.option-content.shown{ background-image:url(shown.png); } 

0
 $('.nav-arrow').on('click', function () {
    $(this).parents('.col-md-6').siblings().find('li').removeClass('subnav---open').find('ul').slideUp('fast');
    $(this).parent().toggleClass('subnav---open').find('ul').first().slideToggle('fast');
});

嗨Solanki - 这可能回答了问题,但如果您使用更完整的示例解释为什么此解决方案有效会更好。 - ste-fu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接